Search code examples
htmlcssblockcenteringquote

How to center a flush-left text block on the longest line in CSS?


In The Elements of Typographic Style, Robert Bringhurst asks designers to center blocks of quoted verse based on the longest line, but to left align all other lines. He writes,

Verse is usually set flush left and ragged right…. But to distinguish verse quotations from their surrounding prose, they should be (indented or) centered on the longest line (p. 41, parentheses mine).

Notice in this example how there are twelve units of space on either side of the longest line, "Jumped over the lazy dog."

------------------------------------------------
|           The quick fox                      |
|           Jumped over the lazy dog           |
|           Lorem ipsum                        |
|           Ad infinitum                       |
------------------------------------------------
1          12          24          36          48

How can you do this in CSS?

Here's what I've tried that doesn't work:

  1. text-align: centered; isn't flush left
  2. margin: auto; on the paragraph's parent requires a fixed width (as far as I know), and then the block is centered on the constant width instead of the dynamic width of the text.
  3. I can center a block with CSS Grid, but I still don't know how to base its width on that of the longest line.

Solution

  • Assuming you have br tags in the text showing your breaks here, what you want to use is display: table;

    #banner-message span{
      margin: 0px auto;
      display: table;
    }
    <div id="banner-message">
      <span>
      The quick fox<br />
      Jumped over the lazy dog <br />
       Lorem Ipsum <br />
       Ad infinitum  
      </span>
    </div>