tags:

views:

75

answers:

3

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-shadow: 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

A: 

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.

Carl Smotricz
In the example provided the h2 is a child or #box. The h2 should be independent of #box and thus have its own margin separate from the the #box.
chris
A: 

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).

tahdhaze09
what do you mean position it relative to the #box div? The h2 is inside the #box div. Shouldn't that make its root element the #box?
chris
+5  A: 

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:

Ionuț G. Stan
thank you, this explains a lot of my passed issues. :)
chris