CSS margin quirks - please help me understand
When using margin on the child element (h2) why does it give margin to the parent(#box) instead? If I change margin to padding it works as expected. Did something change or am I missing something? here is my sample code
<html>
<head>
<style>
#box{
border-radius:10px;
-moz-border-radius:10px;
-webkit-border-radius:10px;
height:200px;
width:500px;
background:red;
box-shadow: 15px 15px 12px grey;
-moz-box-shadow: 15px 15px 12px grey;
-webkit-box-shadow: 15px 15px 12px grey;
text-align:center;
margin-top:0;
}
#box h2{
color:#fff;
text-s开发者_高级运维hadow: 2px 2px 2px #000;
margin-top:75px;/*making this padding gives the effect I thought I could achieve with margin*/
height:50px;
width:200px;
}
</style>
</head>
<body>
<div id="box">
<h2>Fun with CSS3</h2>
</div>
</body>
</html>
also if anyone or everyone could share their experience with margin quirks. THx
It's because of collapsing margins. I hate this "feature", but that's the cause of the rendering "issues" you're having. An excerpt from the specs (emphasis is mine):
If the top and bottom margins of a box are adjoining, then it is possible for margins to collapse through it. In this case, the position of the element depends on its relationship with the other elements whose margins are being collapsed.
- If the element's margins are collapsed with its parent's top margin, the top border edge of the box is defined to be the same as the parent's.
Here's a couple of articles on this subject:
- http://reference.sitepoint.com/css/collapsingmargins
- http://www.researchkitchen.de/blog/archives/css-autoheight-and-margincollapsing.php
My guess is that you've misunderstood the box model. Margin is the space outside, i.e. around a widget, while padding is space inside, i.e. betweeen the widget's outer border and its content.
You may want to look at this diagram: http://www.w3.org/TR/CSS2/box.html of the box model for reference.
I think it's working OK. Padding does just that: it pads the element its applied to. Margin separates elements from each other. So the margin is working as it should. The position of the h2 tag is where it should be. Giving it a margin would push it away from the root element, which in this case is the body. In order for it to move around in the parent element (the #box div), either you would have to position it relative to the #box element, or give it padding (just one method, but not optimal).
精彩评论