Friday, July 30, 2010

The margin-top problem (and solution !)

This is one of the more irritating CSS errors* around - you put something inside a div - and the div takes on the margin-top of its child element.

(*This isn't really an error - it's technically the correct behaviour, but not what a programmer would expect.)

To illustrate - here's a page with multiple divs, with margin-top:0px specifically assigned for the divs.

The page looks like this : [link to page]
The margin-top problem


It should actually look like this : [link to page]
Solved margin-top


Here's an example of the CSS used:

body {
 margin:0;padding:0;text-align:center;background:#222;
 font-family:"Times New Roman", Times, serif;font-size:16px;
}

#box1,.other {
 width:1000px;
 margin:0px auto;
 background:#EEE;
 border-bottom:2px red solid;
}

#box1 {
 height:270px;
 margin-top:0px;
}

.other {
 height:150px;
 margin-top:0px!important;/*makes no difference*/
}


And some of the HTML :
<div id="box1">
 <h1>This h1 tag should have a margin-top. Instead, the div gets it.</h1>
</div>

<div class="other">
 <p style="margin-top:50px;">Text in a styled p tag with a margin-top : again, the parent div takes it.</p>
</div>


To solve this problem, just add a padding-top:1px or a border - any padding or border affecting the top of the parent element will resolve the issue.

As you can see, chrome has this problem. I have tested it on FF, Opera and IE8 with the exact same results.

1 comment:

Anonymous said...

Simple but very often useful. Thanks