Dharman
Dharman

Reputation: 33238

Why are margins in CSS inconsistent and behaving strange?

I was playing with a slideshow in jQuery today. I managed to create it when I noticed strange thing. The div #feature in which the slideshow is placed seems to be somehow glued to its parent element #content. When I add margin: 10px auto to the #feature div, the #content div is also lowered down by 10px relative to its parent element.

Can anyone tell me what have I done wrong here?

Providing you with the whole code would create a mess, but here's a link:

CSS for #feature:

#feature {
    width:940px;
    margin: 10px auto;
    position: relative;
    height:500px;
    overflow: hidden;
    clear: both;
    box-shadow: 0px 0px 5px 2px #000;
}

and CSS for #content:

#content{
    min-height:800px;
    background-color: #fff;
}

My friend noticed an interesting thing. If you add margin-bottom: 30px to #menu the empty 10px space in content is filled correctly although the margin problem is still not solved.

Upvotes: 4

Views: 864

Answers (2)

Sergiy T.
Sergiy T.

Reputation: 1453

Try adding overflow:auto; to #content. It may help.

Adding overflow prevents margins from collapsing

In CSS, the adjoining margins of two or more boxes (which might or might not be siblings) can combine to form a single margin.

from https://www.w3.org/TR/CSS2/box.html#collapsing-margins

Upvotes: 0

Marc B
Marc B

Reputation: 360572

position: relative does just that... makes any element that this applies to have its position become "relative" to its parent container.

#feature is a child of #content, so #feature's position becomes relative to the position of #content. When you add that 10px margin to #feature, it moves down 10px from #content.

Upvotes: 3

Related Questions