4

I have a div with a few words of text in it, which I want to extend as far as the div itself.

In other words, the word-spacing should automatically stretch until the last word reaches the edge of the div.

By reading about text-align: justify, I assumed that's exactly what it was supposed to do. But either I'm mistaken, or I'm doing something wrong: http://jsfiddle.net/rLnrtu0x/1/

To illustrate:

Right now, this is the result:

|text text text text                       |

But I am trying to achieve something like this:

|text        text         text         text|

Am I doing something wrong? Is there another method of accomplishing this?

Mr.Web
  • 5,891
  • 8
  • 37
  • 75
Joe Morano
  • 1,055
  • 7
  • 41
  • 95

2 Answers2

6

If you want to force justify an element, you need to add something semantic in the end.

Use pseudo element is the simplest way. See this snippet.

.justify {
  text-align: justify;
}
.justify:after {
  content: "";
  display: inline-block;
  width: 100%;
  height: 0;
  line-height: 0;
}
<div class="justify">
  Lorem ipsum Ullamco labore quis exercitation ut.  
</div>
Redy S
  • 322
  • 1
  • 6
0

text-align: justify only works on content in any lines of text but the last one – and since you only have one line of text here, you see no effect at all.

Some browsers also support text-align-last specifically for such purposes.

But you can get this to work using a little trick as well: By seeing to it that the text content of your element does not actually constitute the last line – by inserting a pseudo element that takes up full width, so that it is forced to be on a second line.

#justify:after {
    content:"";
    display:inline-block;
    width:100%;
}

http://jsfiddle.net/rLnrtu0x/2/

Apart from the width, display:inline-block is the important part here – if the element was simply inline, the width would have no effect, and if it was block, it would break the whole thing because it would not behave as a fake piece of “text” content in the first place.

If your goal is not only to align simple text, but actual elements (f.e. for an evenly distributed number of list items), then you might also want to look into flexbox.

CBroe
  • 82,033
  • 9
  • 81
  • 132