I have an inner div inside a containing div.
<div id="container">
<div id="inner"></div>
</div>
#container {
width: 100px;
height: 100px;
background-color: red;
}
#inner {
margin: 30px;
width: 40px;
height: 40px;
background-color: black;
}
http://jsfiddle.net/8xUTJ/4/
I expect this to make a small black box centered vertically and horizontally in a bigger red box. Instead I get a black box stuck to the top of the red box, and the red box has the margin-top.
Can someone explain what CSS thinks it is doing here?
Top and bottom margins do not affect inline elements because inline elements flow with content on the page. You can set left and right margins/padding on an inline element but not top or bottom because it would disrupt the flow of content.
When you have specified a width on the object that you have applied margin: 0 auto to, the object will sit centrally within it's parent container. Specifying auto as the second parameter basically tells the browser to automatically determine the left and right margins itself, which it does by setting them equally.
Margin is the space between the border and the next element of your design. Think of the space outside the border and between it and the other elements. This is all the margin. Margin goes around all four sides of the content and you can target and change the margin for each side.
In CSS, adjacent margins can sometimes overlap. This is known as “margin collapse”, and it has a reputation for being quite dastardly. This is an interactive element! Instead of sitting 48px apart, their 24px margins merge together, occupying the same space!
Add overflow:auto
to the #container
div.
jsFiddle example
Or
add a border to the #container
div.
You can read more about this collapsing margin behavior at the W3C.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With