Gemtastic
Gemtastic

Reputation: 6433

Why does <p> put space outside of <div>?

Ok, we can clearly see that there is a space between the top and the <div>. Now, I know this is cause by the margin/padding of the <p> element, but why does it appear outside of the <div> and not inside of it?

body{
  margin: 0px;
  padding: 0px;
  background-color: #808080;
}

#top-wrapper{
  background-color: #ffffff;
  margin: 0px;
  padding: 0px;
}
<body>
  <div id="top-wrapper">
    <p>hello</p>
  </div>
</body>

Upvotes: 0

Views: 104

Answers (2)

Salman Arshad
Salman Arshad

Reputation: 272036

This is the expected behavior. This is because the top margin of paragraph collapsed with the top margin of its parent div (and likewise for bottom margin). This causes the div to appear as if it has a margin.

Margin collapsing is described here:

In CSS, the adjoining margins of two or more boxes (which might or might not be siblings) can combine to form a single margin. Margins that combine this way are said to collapse, and the resulting combined margin is called a collapsed margin.

Upvotes: 2

SW4
SW4

Reputation: 71140

This is due to margin collapsing.

Top and bottom margins of blocks are sometimes combined (collapsed) into a single margin whose size is the largest of the margins combined into it, a behavior known as margin collapsing.

To (prevent this and) provide the behaviour you anticipate, add overflow: auto; to the div, or alternatively overflow:hidden; This enforces the block formatting context

Demo Fiddle

A block formatting context is a part of a visual CSS rendering of a Web page. It is the region in which the layout of block boxes occurs and in which floats interact with each other.

body {
    margin: 0px;
    padding: 0px;
    background-color: #808080;
}
#top-wrapper {
    background-color: #ffffff;
    margin: 0px;
    padding: 0px;
    overflow: auto;
}
<body>
    <div id="top-wrapper">
        <p>hello</p>
    </div>
</body>

Upvotes: 4

Related Questions