Reputation: 21150
Simple one that I can't wrap my head around. Look at the code below; in my understanding of the box model, the 60px margin on #content
should push the entire .main
div down, and the .main
div's margin should start 60px down the page, but in practice the .main
margin overlaps with the #content
margin (here's a codepen)
<head>
<style>
#content{
margin-top:60px;
}
.main{
margin-top:20px;
}
</style>
</head>
<body>
<section id="content">
<div class="main">
<h1>Here's some content</h1>
</div>
</section>
</body>
Why is this happening?
Edit: And what are some proposed solutions? Note that adding overflow:hidden
to the parent element is one solution but it isn't an appropriate fix; if I put an h1
inside .main
and try to put a top-margin on that, the same issue happens - and I don't want to be applying overflow:hidden
to everything!
Upvotes: 0
Views: 70
Reputation: 1018
This is default behavior of the box model as per w3c (reference)
Now to overcome this you need to float the elements as below
#content {
margin-top: 20px;
float: left;
width: 100%;
}
.main{
float: left;
width: 100%;
margin-top: 40px;
}
Upvotes: 0
Reputation: 363
That is happening because you have not specified height of your content div. So when you give in something like .main in your #content div then the content div takes up the height of .main div because that is what the content requires.
So to make it a bit clear, if your .main div is taking up a height of 50px then #content will also be just 50px in height because you have not specified otherwise. So the margin-top of .main div is collapsing with .margin-top of #content.
Upvotes: 0
Reputation: 1923
It's because of collapsing margins which you can read about here.
Upvotes: 1