How to center-justify the last line of text in CSS?
Solution 1:
You can use the text-align-last
property
.center-justified {
text-align: justify;
text-align-last: center;
}
Here is a compatibility table : https://developer.mozilla.org/en-US/docs/Web/CSS/text-align-last#Browser_compatibility.
Works in all browsers except for Safari (both Mac and iOS), including Internet Explorer.
Also in Internet Explorer, only works with text-align: justify
(no other values of text-align
) and start
and end
are not supported.
Solution 2:
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.
What's going on?
-
text-align: justify;
makes sure the text fills the full width of thediv
it is enclosed in. -
margin: 0 auto;
is actually a shorthand for four rules:- The first value is used for the
margin-top
andmargin-bottom
rules. The whole thing therefore meansmargin-top: 0; margin-bottom: 0
, i.e. no margins above or below thediv
. - The second value is used for the
margin-left
andmargin-right
rules. So this rule results inmargin-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.
However, this would not work without
- The first value is used for the
-
width: 30em;
, which limits the width of thediv
. Only when the width is restricted is there some whitespace left over formargin: auto
to distribute. Without this rule thediv
would take up all available horizontal space, and you'd lose the centering effect.
Solution 3:
its working with this code
text-align: justify; text-align-last: center;
Solution 4:
There doesn't appear to be a way. You can fake it by using justify and then wrapping the last line of text in a span and setting just that to text align center. It works ok for small blocks of text but is not a useful approach to large quantities of text or dynamic text.
I suggest finding somebody at Adobe who's involved in their W3C work and nagging them to bring up right/left/center justification in their next meeting. If anyone's gonna be able to push for basic typography features in CSS it'd be Adobe.