For people looking for getting text that is both centered and justified, the following should work:
<div class="center-justified">...lots and lots of text...</div>
With the following CSS rule (adjust the width
property as needed):
.center-justified {
text-align: justify;
margin: 0 auto;
width: 30em;
}
Here's the live demo.
text-align: justify;
makes sure the text fills the full width of the div
it is enclosed in.margin: 0 auto;
is actually a shorthand for four rules:
margin-top
and margin-bottom
rules.
The whole thing therefore means margin-top: 0; margin-bottom: 0
, i.e. no margins above or below the div
.margin-left
and margin-right
rules.
So this rule results in margin-left: auto; margin-right: auto
.
This is the clever bit: it tells the browser to take whatever space is available on the sides and distribute it evenly on left and right.
The result is centered text.width: 30em;
, which limits the width of the div
.
Only when the width is restricted is there some whitespace left over for margin: auto
to distribute.
Without this rule the div
would take up all available horizontal space, and you'd lose the centering effect.