Thursday, April 16, 2009

Justifying a single line of text using HTML and CSS

If you have the need to match a single line of text to the width of its container, you may experience some of the frustration that I have gone through. There is a pseudo-fix for IE only, but since I generally oppose the very existence of IE I won't even bother mentioning it. (that is sarcastic, but IE gives me enough grief that I almost mean it)

Here is the issue: the css property text-align has an option of "justify" which causes inline text to flow to the full width of the container. Except for the last line. 

If you have a paragraph that is text-align:justify, all the lines will stretch to the full container width with the exception of the last, which will left-align.

I needed a tag line to match the width of a logo and I didn't want to use a graphic. The tag line was only one line of text and was supposed to match the width. Since it is just a single line, it was treated as the last line of a paragraph and not allowed to fill the width.

I played with the font size, letter spacing and padding, but in the end I used a little HTML to trick my page into working.

After the last word, I put a space in the HTML, and then 5 consecutive non breaking space characters back-to-back like this:       - this back-to-back string of these characters is interpreted by all current major browsers as a "word" and forced onto the next line, leaving the first line as just the tagline.

DEMO:
Here is my single line of text, text-aligned justify              


This isn't a perfect solution since it adds padding below the tagline, but I can accomodate that (I just put an overflow:hidden on my container and it kept it constrained properly). Also this is definitely a hack so not ideal, but I can be pragmatic and say I got what I needed working.

Leave any thoughts in the comments!

7 Comments:

Blogger diederik said...

thank you this is i nice hack

1:02 AM  
Anonymous Anonymous said...

thanks for this posting. I nearly broke my head to find a solution, but there seems to be no better one.

11:24 AM  
Anonymous Curtis said...

I can't believe this isn't built into CSS somehow (perhaps it is, but I haven't found it). So I'm thankful for your hack. I tried   in succession but your tip of five in a row was the ticket for success.
Thanks...

1:28 PM  
Anonymous Discipulus said...

Not the prettiest solution but a great help non the less. Thanks!

12:33 PM  
Anonymous Anonymous said...

Really helped save my day!

2:32 AM  
Anonymous Anonymous said...

just trying to make a single for clan names and then add a send to my forum

8:02 AM  
Blogger wallace said...

Your blog is well written.
oklahoma city escorts

10:33 PM  

Post a Comment

<< Home