How to center-justify the last line of text in CSS?

后端 未结 10 1678
余生分开走
余生分开走 2020-12-02 08:23

How can I center-justify text?

Currently, justify does not center the last line.

10条回答
  •  -上瘾入骨i
    2020-12-02 09:25

    For people looking for getting text that is both centered and justified, the following should work:

    ...lots and lots of text...

    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?

    1. text-align: justify; makes sure the text fills the full width of the div it is enclosed in.
    2. margin: 0 auto; is actually a shorthand for four rules:
      • The first value is used for the 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.
      • The second value is used for the 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.
        However, this would not work without
    3. 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.

提交回复
热议问题