With flexbox being supported by all the latest browsers out there, and it being five years since the IE8 requirement was mentioned by the author, I wanted to have some fun building a new solution using that.
A variety of examples getting more complicated:
https://jsfiddle.net/0mL79b4h/1/
https://jsfiddle.net/0mL79b4h/2/
CSS
div {
display: flex;
align-items: center;
}
div:before,
div:after {
border: 1px solid #000000;
border-radius: 2px;
height: 2px;
display: block;
content: "";
flex: 1;
width: 100%;
}
h1 {
text-align: center;
margin: 8px;
}
HTML
<div>
<h1>Example Text</h1>
</div>
<div>
<h1>Multi-Line<br>Example Text</h1>
</div>
Pros:
- Uses flexbox!
- Super simple HTML.
- Left and right sides can be adjusted for asymmetry.
- Zero background issues, no inheriting colors, etc.
- Fluid width.
- Multi-Line support.
- Left/Center/Right/Custom Alignment: Just adjust the flex property separately for the before and after elements, higher numbers will dedicate more space to that side. Remove one entirely to left or right align it.
- Interesting effects by playing with the border style (I actually chose a round border in this example). Set height to 0px and use border-top instead for a generic line.
Cons:
- Uses flexbox. Call me lazy, but I didn't build in any backward compatibility in this example so it'll look odd on a browser that supports psuedo elements but doesn't support flexbox, although last I checked that was Chrome (Firefox, etc), which are all automatically updated anyway. Might want to use some Modernizr.