Cross-browser CSS: Justify last line of text in a paragraph

Normally if you use CSS to justify text, the last line of text is aligned left rather than justified as on other lines. This is the desired behavior in most instances but for some layouts you may want to justify the last line as text as well. Following is a cross-browser method you can use which will work in IE6+ in addition to popular modern browsers. (This method is also useful if you want to justify just one line of text such as in a heading.)

Tested in IE6, IE7, IE8, FF, Safari, Chrome

Regular Justified Text vs. Text Using This Method:

CSS:

p, h1 {
	text-align: justify;
	text-align-last: justify;
}

p:after, h1:after {
	content: "";
	display: inline-block;
	width: 100%;
}

A paragraph tag (p) and a header (h1) are used above just as examples. You can substitute any block level html elements instead such as a div.

See it in action: http://www.webcodeshare.com/agx3ZWJjb2Rlc2hhcmVyDwsSB1dlYmNvZGUY8vsQDA

Caveat: One issue with this method is that extra space is added to the bottom of html elements in browsers other than IE. It appears to happen as a result of how line-height spacing is added by browsers to the last visible line of text.

Update: You can add a negative bottom margin to the elements you are justifying (such as “margin-bottom: -1.2em;”) to remove extra spacing added by :after. You will need to add a margin back for IE.

About these ads
Leave a comment

4 Comments

  1. Robert

     /  June 14, 2013

    All justified like that looks bad, I need it to adjust words throughout the paragraph so the last line doesn’t look any more spaced out than the other lines. I have a specific need to do that – ashame there doesn’t seem to be an answer.

    Reply
    • I agree it’s usually a bad idea to justify the last line for most designs on the web.

      There isn’t a really good practical way to adjust the spacing of text on that level on the web currently unfortunately.

      Reply
  2. OMG. I love you! I’ve been looking for a good tutorial on this. Nothing worked, until I found your post. Thanks!

    Reply

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.