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: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%;
About these ads
Tagged , ,

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

  1. Rob says:

    Cheers for this, helped me a bunch today :)

  2. Matt Bivins says:

    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!

  3. Alex says:

    Thanks a lot for this! I’ve been looking all day for a nice clean solution and this worked like a charm.


  4. Skip says:

    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?

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Get every new post delivered to your Inbox.

Join 1,036 other followers

%d bloggers like this: