Search code examples
htmlcssxhtmllinevertical-alignment

Add centered text to the middle of a horizontal rule


I'm wondering what options one has in xhtml 1.0 strict to create a line on both sides of text like-so:

Section one
----------------------- Next section -----------------------
Section two

I've thought of doing some fancy things like this:

<div style="float:left; width: 44%;"><hr/></div>
<div style="float:right; width: 44%;"><hr/></div>
Next section

Or alternatively, because the above has problems with alignment (both vertical and horizontal):

<table><tr>
<td style="width:47%"><hr/></td>
<td style="vertical-align:middle; text-align: center">Next section</td>
<td style="width:47%"><hr/></td>
</tr></table>

This also has alignment problems, which I solve with this mess:

<table><tr>
<td style="border-bottom: 1px solid gray; width: 47%">&nbsp;</td>
<td style="vertical-align:middle;text-align:center" rowspan="2">Next section</td>
<td style="border-bottom: 1px solid gray; width: 47%">&nbsp;</td>
</tr><tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr></table>

In addition to the alignment problems, both options feel 'fudgy', and I'd be much obliged if you happened to have seen this before and know of an elegant solution.


Solution

  • Flexbox is the solution:

    .separator {
      display: flex;
      align-items: center;
      text-align: center;
    }
    
    .separator::before,
    .separator::after {
      content: '';
      flex: 1;
      border-bottom: 1px solid #000;
    }
    
    .separator:not(:empty)::before {
      margin-right: .25em;
    }
    
    .separator:not(:empty)::after {
      margin-left: .25em;
    }
    <div class="separator">Next section</div>

    Nowadays every browser supports it, and you can ensure compatibility with decade-old browsers by adding respective vendor prefixes if needed. It would degrade gracefully anyways.