How can I expand the text to the width of its container?


Joe Morano

I have a div that contains some text that I want to expand into the div itself.

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

From reading about text-align: justify, I think this is exactly what it should do. But either I got it wrong, or I did something wrong : http://jsfiddle.net/rLnrtu0x/1/

To show:

Now this is the result:

|text text text text                       |

But I am trying to achieve the following:

|text        text         text         text|

Am I doing something wrong? Is there another way to do this?

Crowe

text-align: justifyOnly works for any text content except the last line, and since there's only one line of text here, you won't see any effect at all.

Some browsers also provide support specifically for this purpose .text-align-last

However, you can also use a few tricks to make it work: by making sure the element's text content does n't actually make up the last line - by inserting a pseudo-element that takes up the full width, thus forcing it to be on the second line.

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

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

Except width, display:inline-blockhere's the important part - if the element is simple inline, the element widthwill be invalid, if the element is , blockit will break the whole content, since it doesn't behave as a fake "text" content in the first place.

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

Related


How can I expand the text to the width of its container?

Joe Morano I have a div that contains some text that I want to expand into the div itself. In other words, the word spacing should automatically stretch until the last word reaches the edge of the div. From reading about text-align: justify, I think this is ex

How can I expand the text to the width of its container?

Joe Morano I have a div that contains some text that I want to expand into the div itself. In other words, the word spacing should automatically stretch until the last word reaches the edge of the div. From reading about text-align: justify, I think this is ex

How can I expand the text to the width of its container?

Joe Morano I have a div that contains some text that I want to expand into the div itself. In other words, the word spacing should automatically stretch until the last word reaches the edge of the div. From reading about text-align: justify, I think this is ex

How can I expand the text to the width of its container?

Joe Morano I have a div that contains some text that I want to expand into the div itself. In other words, the word spacing should automatically stretch until the last word reaches the edge of the div. From reading about text-align: justify, I think this is ex