Confused over hr margins!

Hello, folks!

I am having some unexpected results when trying to set margins on an hr. Basically…I can only get the bottom margin of the hr to actually display.

Here is some sample code if it helps:


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<style>
.left {
  background: #ff0000;  
  width: 400px;
  float: left;
}
.right{
  background: #00ff00; 
  width: 400px; 
  float: left;
}
hr {
  height:2px;
  width: 100%;
  background: #efefef;
  margin: 70px 0 70px 0;
  clear: both;
}
</style>
</head>
<body>
  <div class="left">hello!</div>
  <div class="right">hello!</div>
  <hr />
  <div class="left">hello!</div>
  <div class="right">hello!</div>
</body>
</html>

Running that will result in the two divs “left” and “right” followed immediately by an hr (with no margin at all). Then a 70px vertical margin and finally two more instances of the “left” and “right” divs.

Any ideas? I have the feeling I am missing something very very simple and am headed for a Homer Simpson “DOH!” moment.

Thank you very much!

Floats are removed from the flow so the margin-top on your hr slides under the float until it hits something solid (i.e something non floated like the top of the containing block) . As there was nothing there the margin had no effect.

If you put your floats in a container with a 1px padding top then the margin of the hr would still slide under the float but would take effect from that 1px padding on the parent. That wouldn’t really help you much because then you would need to always take into account the height of the float.

Therefore for consistent spacing after floats then put a margin-bottom on the float itself which will push a static cleared element further away. Or if the layout allows then float the other element also but you usually don’t want to float everything if it can be avoided.

So basically…floated elements will only display a vertical margin with other floated elements after a clear?

Going to just re-write what I have so far to use borders. Sounds like good advice :smiley:

The top margin will not get applied from the element above because the element above is a float and the margins will slide under the float.

You could float the hr and then the margin will take effect or put the margin botton on the float above instead.


hr {
  height:2px;
  width: 100&#37;;
[B]  background: #efefef;
    color:#efefef;
    border:none;[/B]
  margin: 70px 0 70px 0;
  clear: both;
 [B]   float:left;[/B]
}


The hr is displayed differently cross browser and some browsers use background for the color and some use color which means that you need to specify both.

hrs are useful for when css is turned off but usually I set them to display:none and then style an existing elements top or bottom border instead for more reliable rendering.