Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inner div's margin affecting containing div's margin

Tags:

I have an inner div inside a containing div.

HTML

<div id="container">
  <div id="inner"></div>
</div>

CSS

#container {
    width: 100px;
    height: 100px;
    background-color: red;
}
#inner {
    margin: 30px;
    width: 40px;
    height: 40px;
    background-color: black;
}

Fiddle

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?

like image 897
Bobby Avatar asked Sep 28 '12 00:09

Bobby


People also ask

Does setting margin top and margin bottom have an affect on an inline element?

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.

What happens when margin Auto is applied on a span of fixed height?

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.

Is margin inside or outside?

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.

Do margins overlap CSS?

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!


1 Answers

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.

like image 129
j08691 Avatar answered Oct 01 '22 17:10

j08691