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!

0 Comments:

Post a Comment

<< Home