0

HTML:

<div>  
    <p>
        Lorem ipsum dolor sit amet.
    </p>  
</div>  

CSS:

p {
    margin-top: 20px;
}  

div {
    width: 400px;
    height: 80px;
}

Margin means space around a box FROM ITS PARENT. right? why my p tag doen't get top margin from div? instead from body. I mean p and div get attached together.
I know with floating we can solve this. or applying border or padding.
My question is: Is there any collapsing? what's happening?

EDIT: Sorry guys.
I know the solution as I said. I want to know the underlying concept.

Margin applies to OUTSIDE of an element.

But Consider p tag. it is INSIDE. whatever margin we give to p tag, should only apply to its siblings. not outer elements like its parent or div.

3 Answers3

1

This is called Margin Collapsing.

One solution is adding a padding to your parent element:

p {
    margin-top: 20px;
    background: yellow;
}  

div {
    width: 400px;
    height: 80px;
    background: red;
    padding-top: 1px;
}

Another solution is adding overflow to your parent element:

div {
    width: 400px;
    height: 80px;
    background: red;
    overflow: hidden;
}

See this jsFiddle Demo.

dashtinejad
  • 6,193
  • 4
  • 28
  • 44
0

You should use padding:

p { padding-top: 20px; }
div { width: 400px; height: 80px; background-color:blue}

http://jsfiddle.net/t1acatL1/1/

Typo
  • 1,875
  • 1
  • 19
  • 32
0

This is happening because you didn't set any postion to div element.

Set position:absolute to div element.

div{
   position: absolute;
   width: 400px;
   height: 80px;
}

That's it. Now check it.

Viswanath Donthi
  • 1,791
  • 1
  • 11
  • 12