-->

Justify text to fill a div

2019-01-28 18:22发布

问题:

What i want to do is something like this:

1 2 3 4 5
6       7
8 9 10 11

With this code:

<div style="text-align: justify;">
1 2 3 4 5
<br>
6 7
<br>
8 9 10 11
</div>

But it doesn't work, and displays like this:

1 2 3 4 5
6 7
8 9 10 11

回答1:

In DTP and word processing applications, this option is known as 'force justify'. Unfortunately, this is not an option in CSS.



回答2:

Justify only takes up the complete line when the text wraps to the next line. If you want it to wrap you need a narrower div width, and you need to remove your <br />s.

You could start with something like this though (just not sure how to place the 7 at the same place as the 5 and the 11):

<div style="text-align: justify;">
1 2 3 4 5
<br>
<span style="text-align:left;">6</span>
<span style="float:right;">7</span>
<br>
8 9 10 11
</div>


回答3:

Another option albeit a little ugly with the &nbsp;.

Live Demo

<div style="width:60px;text-align: justify;">
    1 2 3 4 5 6 &nbsp; &nbsp; &nbsp; &nbsp; 7 8 9 10 11
</div>

Another Options without the nbsp;

<div style="width:60px;text-align: justify;">
    1 2 3 4 5 6 <span style="width:30px; display:inline-block;"></span> 7 8 9 10 11
</div>


回答4:

Here is some more tricks to play around to get your solution:

<pre><div>1 2 3 4<br/>4     6<br/>7 8 9 0</div></pre>

See the demo here