Justifying text

I recently had a project where the client wanted the text justified. Browsers do a bad job of justifying text, but under controled circumstances it’s not too bad. IE is actually better at handling justified text because because you can control how the text is justified:

text-justify: [auto | distribute | inter-word | newspaper]

And you can control justification on the last line of text:

text-align-last: [auto | center | inherit | justify | left | right]

For this project the last line of text needed to be justified, which wasn’t happening in Firefox and Safari. The solution was to add addition content using CSS :after psuedo-selector:

p:after
{
	content: " ____________________________________________________________";
	line-height: 0;
	visibility: hidden
}

Now the last line appears justified in all browsers.

(Updated 8/28/08 to change color: #ffffff to visibility: hidden)

4 Responses to “Justifying text”

  1. Rene Olsthoorn says:

    In FireFox 3, you see the underscore line: ___________
    It seems that the line-height: 0; is not working….

    Very unfortunately, because I would really like to justify the last line in FireFox.

  2. william says:

    You will see the underscore unless you set the color to be the same as the background. In the example, the color for p:after is white, which is the color of the body background.

  3. Rene Olsthoorn says:

    William, thanks for your reply.
    I found the solution in my case. I will describe it here, for people with the same problem:

    I pre-calculated whether the last line should be justified. In that case, I gave the paragraph a special classname “lastjustify”.

    For that paragraph, I decreased the bottom-margin by -0.5 em. I also made the p.lastjustify invisible.

    Right now, the IE content looks exactly the same as the Firefox content.

    Here my css extract:

    p.lastjustify
    {
    margin : 0px 0px -0.5em 0px;
    }

    p.lastjustify:after
    {
    content: ” _________________________________________”;
    line-height: 0px;
    color: #ffffff;
    visibility: hidden;
    }

    Last remark:
    These two css definitions are part of my firefox.css, which is ONLY loaded when the browser is not Internet Explorer.

    You can do that by using:

    if (navigator.userAgent.indexOf(’MSIE’) == -1)
    {
    var headID = document.getElementsByTagName(”head”)[0];
    var cssNode = document.createElement(’link’);
    cssNode.type = ‘text/css’;
    cssNode.rel = ’stylesheet’;
    cssNode.href = ”;
    cssNode.media = ’screen’;
    headID.appendChild(cssNode);
    }

    Hope this helps for people having the same problem.
    René Olsthoorn.

  4. william says:

    Nice work, thank you for sharing your solution. The -.5em removes the extra space beneath the justified paragraph, and using visibility to hide the content is better than changing the color. I updated my code to use visibility.

Leave a Reply