Centered heading overlaying a horizontal line with CSS

After the introductory post I’m going to start writing about CSS, even when it’s not my favourite language as I’m always feeling I spend way too much time for things that should be simpler.

Four weeks ago, while I was implementing a CSS design, I faced the problem of centering the heading overlaying a horizontal line and I found this great post by Louis Lazaris.

Unfortunately, none of the solutions there were valid for me as I needed also to have transparent background. So I started to play with the pseudo-elements till I got the solution.

Giving height and background-color to the pseudo elements :before and :after, together with negative margins of the same size than the heading, defined as 50 %, makes the trick, that I think it’s easy to understand seeing it in action on a fiddle.

Besides allowing any kind of background, my solution doesn’t add any extra HTML tag and scales with every size of text.

h1 {
 overflow: hidden;
 text-align: center;
}
h1:before,
h1:after {
 background-color: #000;
 content: "";
 display: inline-block;
 height: 1px;
 position: relative;
 vertical-align: middle;
 width: 50%;
}
h1:before {
 right: 0.5em;
 margin-left: -50%;
}
h1:after {
 left: 0.5em;
 margin-right: -50%;
}

22 thoughts on “Centered heading overlaying a horizontal line with CSS

  1. Pablo: have used this twice on HTML that I didn’t have access to but needed to style…this trick saved the day. Many thanks!

    For any other lucky souls that found this site, but don’t need their header centered, all you have to do of course is leave out the “text-align: center” in the h1 and play with the width, and the negative left and right margins, of the pseudo elements. Easy peasy!

  2. What if I use this, it’s going to make every single H1 tag on my site like that right? how would I prevent that to just a select or particular set of H1 tags?

  3. Hello Pablo, I’m so glad I found your post because I’ve been pulling my hair out about this!

    The only thing that your coding has done is also put lines on the side of my logo on the header. How can I change that to only be in my headline?

    Thanks a million,
    Sandra

    • Hi Sandra!

      Without seeing your markup I understand you have wrapped your logo with the H1 tag. So I see two possible solutions: you either wrap your logo with a different tag or you use a class selector for those elements that need to be styled.

      Cheers, Pablo.

  4. Pingback: vclever digital design & marketing » How to style a heading with horizontal lines either side using CSS

  5. Pingback: How to style a heading with horizontal lines either side using CSS

  6. Pingback: wordpress-846582-3443679.cloudwaysapps.com » How to style a heading with horizontal lines either side using CSS

Leave a reply to Matt Bivins Cancel reply