2

I noticed this strange behavior years ago back when I was first learning HTML, and still don't understand it.

Both jsfiddles are based on the following HTML:

<div class="parent">
    <div class="child">
        Child content
    </div>
</div>

In the first jsfiddle, I'm adding a margin-top to the child element, yet the entire parent element shifts downward: http://jsfiddle.net/flyingL123/uUgVz/

In the next jsfiddle, the only thing I'm changing is adding a border to the parent element, and now the parent element no longer shifts down the page: http://jsfiddle.net/flyingL123/uUgVz/1/

Why don't both jsfiddles behave the same? Why is the parent element effected by the margin-top on the child element in the case when the parent element does not have a border?

flyingL123
  • 7,686
  • 11
  • 66
  • 135

3 Answers3

0

It is because the childis not empty (height!==0)

<div class="parent">
    <div class="child">
        Child content
    </div>
</div>

is the same as

<div class="parent">
    <div></div>
    <div class="child">
        Child content
    </div>
</div>

empty element will be used as wrapper

enter image description here

and adding border to the parent is like saying hey now we want to see something which is the same as just adding a letter:

<div class="parent">
    m
    <div class="child">
        Child content
    </div>
</div>

-Demo-

Note that you are applying the style on the parent element and not the child, that means the first and all next notempty childif they dont have a style set will adopt the parent style

Gildas.Tambo
  • 22,173
  • 7
  • 50
  • 78
0

It has to do with how block elements are rendered. By default, divs don't hide their contents, it means that anything inside a div that results being larger than its parent would stick out of it, like the margin of your child element, however you can use the overflow: hidden attribute so that the content is limited only to the size of the container, and thus, making your margin to push from the inside of your div, since it can't stick out of it:

See the updated fiddle:

CSS:

.parent{
    width:300px;
    background-color:#666;
    color:white;
    overflow: hidden;
}

.child{
    margin-top:50px;
}

But in case you still want the children to stick out of the parent but to be pushed down, you can set the container's padding value instead of the child's margin value, see this other fiddle:

CSS:

.parent{
    width:300px;
    background-color:#666;
    color:white;
    padding-top: 50px;
}

.child{
    /* margin-top:50px; */
}
arielnmz
  • 8,354
  • 9
  • 38
  • 66
0

The effect you described is caused by Margin Collapsing

Go through this Stackoverflow to learn how to remove the margin collapsing.

Community
  • 1
  • 1
Barun
  • 4,245
  • 4
  • 23
  • 29