<hr> element css – removing the gaps in IE6 and IE7

Applying css styling to the horizontal rule <hr> element is a little problematic, thanks in most part to non-standard approach of IE6 and IE7 or less. Let’s start off with colour. IE7 and under use the color selector to set the colour of the <hr>. Firefox, Opera, Chrome, Safari and IE8 all use background-color. So with css as follows:

hr{height:10px;color:red;background-color:blue}

Firefox and Opera give me a blue <hr> with a faintly discernible red border, Chrome, Safari and IE8 give me a blue <hr> with a grey border, and IE6/7 give me a red <hr> with no border. So I need to set both color and background-color and remove the border to get a consistent effect.

So far so good, but the next problem is the margin. IE applies a default 8px margin top and bottom, which is added to any margin applied via css. So, with css as follows:

hr{height:10px;color:blue;background-color:blue;border:none;margin:10px 0}

Firefox, Opera, Chrome, Safari and IE8 are consistent but IE6/7 have a much bigger margin. My only solution is to use some conditional css to target IE6/7

<!--[if lte IE 7]>
<style type="text/css">
hr{margin:2px 0}
</style>
<![endif]-->

So to achieve a 10px margin in IE I’m compensating for the 8px applied by only applying a 2px margin. Job done.

Here’s a test page if you want to have a look for yourself.

There is another solution to all this of course, which is to dispense with the <hr> element altogether and use border instead…

Useful? Interesting? Leave me a comment