Posted on June 11, 2015 at 6:01 pm by Andrew Arnott

How to style a heading with horizontal lines either side using CSS


You’d think it’d be the simplest of things to create a centred heading with horizontal lines either side of it, but as is so often the case in web design, when you throw in lots of different browsers and devices, things aren’t so simple after all.

The problem

As with anything in HTML and CSS, there are a number of different ways you can achieve this effect. Most involve adding a <span> which I’m not too keen on – it’s much cleaner to just have header tags (e.g. <h1> or <h2>) and not be worrying about adding a <span> as well, especially if a client has to input these themselves. The span solutions also have the drawback of needing a background to cover the horizontal line; this means they can’t be used on an image or gradient background. I also wanted to avoid using JavaScript or images. Cross-browser compatibility was a must too – unless a project has any more specific requirements, we usually look to make it compatible back to Internet Explorer 8.

When researching the best solution, I found this excellent post which covers a number of methods, but my favourite solution was actually posted in the comments in response to the article.

The ‘best’ solution

This method, taken from this post here, is a very neat way of creating the appearance I was looking for. It doesn’t require any <span> elements and is beautiful in its simplicity.  It’s compatible with major browsers all the way back to IE8. IE7 and IE6 don’t support pseudo elements like :before so it won’t work with them, but it does degrade nicely (it just doesn’t show the lines).

Here’s the CSS

h1 {
 overflow: hidden;
 text-align: center;
h1:after {
 background-color: #333;
 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%;

To change the colour and thickness of the line, change the background-color (#333) and height (1px) respectively.

The horizontal line will stretch across the entire width of the containing element, so if you want it to cover a smaller width, simply use an appropriately-sized containing element.

Here’s how it looks:

Horizontal Line Heading

A very tidy end-product made with neat CSS which renders perfectly in all major browsers right back to IE8 (and still looks fine in IE7/6 but without the lines). A big thanks to Pablo Villoslada Puigcerber for his solution.

Filed under: All, Design, Technical stuff | No comments yet

Leave a Reply