One design pattern that I get passed off to me fairly frequently is a headline with a centered line filling the space to the right or on both sides. Here is an example:

I’ve found a few different ways to accomplish this effect in the past. They worked but always felt a little hacky and confusing. However, with flexbox and pseudo elements in CSS, accomplishing this look is pretty easy.
With flexbox, we are able to easily align content vertically. We can also add spacing between elements using column-gap
. That gives us the building blocks we need to implement this design pattern. Let’s start with the HTML.
<div class="centered-headline">Explore the</div>
Since we will use flexbox on this elements, we will add the display: flex;
to it. We want the items of the headline to be vertically aligned to the center, so we will also add a align-items: center
. We also want a little breathing room between the text and the horizontal lines so we will use a column-gap
. I also will add in a white-space
rule to prevent our headline from wrapping onto multiple lines. We are going to make our lines 100% wide so, by default, the browser will add a line break between multiple words to allow the lines to fill as much space as possible. We want to keep our headline on a single line.
.centered-headline {
display: flex;
align-items: center;
column-gap: 1rem;
white-space: nowrap;
}
Now we can add the lines on either side of our text using the before
and after
CSS pseudo elements. This can easily be done by creating each element as 100% width, 1 pixel high elements with a background color. This will be our line. Pseudo elements require a content
value to be displayed. Since we just want the background color to be shown, and no actual content, we can just make it an empty string.
.centered-headline:before,
.centered-headline:after {
content: '';
height: 1px;
width: 100%;
background-color: red;
}
And that is all we need. Here is the result of the above HTML and CSS:
