CSS Top-Margin Issue
Does anyone know why I don't get a top-margin in the first div based on the CSS below? This renders the same in Chrome, Safari and Firefox 4 running on Mac OSX Lion (rendered the same in Snow Leopard). I would expect the first item to display with a 5px margin all the way around the inner div (except for the bottom obviously) and not just on the right and left. Why would the开发者_StackOverflow中文版 margin not also be applied to the top? Even if I specify margin-top:5px in the CSS it still doesn't render as I would expect.
<!DOCTYPE html>
<html>
<head>
<style>
.outer{
background-color:red;
width:100px;
height:100px;
margin-bottom:20px;
}
.inner{
background-color:white;
margin:5px;
}
.shim{
height:1px;
}
.outer2{
background-color:red;
width:100px;
height:100px;
margin-bottom:20px;
padding:5px;
}
.inner2{
background-color:white;
}
</style>
</head>
<body>
<div class="outer">
<div class="inner">
Margin
</div>
</div>
<div class="outer">
<div class="shim"></div>
<div class="inner">
Margin+Shim
</div>
</div>
<div class="outer2">
<div class="inner2">
Padding
</div>
</div>
</body>
</html>
You're running into a common problem called "collapsing margins." Basically, whenever vertical margins touch (even when one element is inside another element), the margins collapse.
In this case your margin property on the inner div is collapsing into the margin-bottom: 20px;
property on your outer div. To fix this, add a little padding or a border around the containing element.
Just tried this using your code and it works: http://jsfiddle.net/hWPyD/2/
More info on collapsing margins: http://www.w3.org/TR/CSS2/box.html#collapsing-margins
Its because there is a default margin and padding on html tags. Use a reset like this one to remove all of the browser defaults. (I highly recommend doing this)
精彩评论