I’m mainly writing this here so I’ll find it again in a few years when I need to do this and can’t remember how I did it before.
Say you want a nice looking, centered text header integrated with a horizontal rule, with the line on both sides of the text and a bit of a gap, like this:
Here’s My Nice Header
The only HTML involved there is this:
<h4 class="my-nice-header">Here's My Nice Header</h4>
Besides Flexbox, obviously, I’m leaning heavily into CSS Pseudo-elements to make this work. It occurred to me immediately that I could use the ::before
and ::after
pseudo-elements for the lines, but my real flash of insight (at least it felt like a flash of insight to me) was using the ::first-line
pseudo-element to apply Flexbox styling to the text itself, without needing anything like a nested <span>
tag.
Here’s the exact CSS code I’ve included in the page to render this header:
.my-nice-header { align-items: center; display: flex; gap: 1rem; width: 100%; } .my-nice-header::before, .my-nice-header::after { background: gainsboro; content: ''; display: block; flex: 1; height: 1px; } .my-nice-header::first-line { display: block; flex: 1; text-align: center; }
Note: I removed some font styling and margins that aren’t pertinent to the actual “trick” itself. I left in the background color, because you need to specify some color for the lines not to be invisible.