Overflow text left and right

How to center text with css so that it overflows both left and right? I see issues here that make the text overflow left rather than right, but I want it to look as if the text has been enlarged.

<body> <div class="page"> SOMEHEADER </div> </body> 

-

 .page { overflow:hidden; width:70%; text-align:center; margin:0 auto; font-size:8em; word-wrap:none; } 

Here's a fiddle with a demonstration of what I'm talking about.

+6
source share
2 answers

Not the most elegant solution, but it seems to work.

HTML:

 <div class="page"> <div> SOMEHEADER </div> </div> 

CSS

 .page > div { margin: 0 -1000%; } 

Example: http://jsfiddle.net/grc4/w36mX/

This method works by stretching the inner div so that it is wide enough to fully match its contents (without wrapping / overflow). Then the content is centered ( text-align: center ) and trimmed to size by an external div ( overflow: hidden ).

The tricky part is making the inner div wide enough to fit the text. Whenever it is not wide enough, the text will overflow to the right so that it is not properly centered (as seen in the original jsFiddle).

Using negative fields , you can stretch an element by a certain amount both on the left and on the right. If you know that the text size is 400 pixels, for example, you can use margin: 0 -200px so that the inner div is always at least 400 pixels wide (200 pixels to the left and 200 pixels to the right). When you do not know the exact size of the text, you can either use percentages or a really high px value.

margin: 0 -100% stretches the div 100% of its original size to the left and 100% right again, making it 3 times bigger than the div .page . The text has a width of about 900px, so this method will stop working if the div .page reaches a width of 300px (try resizing your browser in jsFiddle using margin: 0 -100% to understand what I mean).

margin: 0 -1000% stretches the div to make it 21 times larger, which is usually enough to fit the text.

+8
source

See this demo: http://jsfiddle.net/QZCuY/3/ I tested it in recent versions of Chrome, FF, and IE7-9

HTML ( <div class="text"> added):

 <div class="page"> <div class="text"> SOMEHEADER </div> </div> <p> How do I get the header to overflow left <u>and</u> right instead of just to the right? </p> 

CSS ( .page has two new properties and a new .text class):

 body { background-color:green; } .page { position:relative; height:1em; overflow:hidden; background-color:red; width:70%; text-align:center; margin:0 auto; font-size:8em; word-wrap:none; } p { width:70%; margin:50px auto 0; text-align:center; font-size:2em; } .text { position:absolute; right:-50%; left:-50%; }​ 
+1
source

All Articles