bdesham
bdesham

Reputation: 16089

Why does this small padding value result in such a large amount of space?

Consider this basic HTML:

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

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

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

and CSS:

div {
    background-color: lightgray;
    padding-top: 0rem;
    padding-left: 1rem;
}

(Fiddle here.)

When the padding-top is set to 0rem (or if that line is omitted), there is very little gray background above the text. But if I set padding-top: 0.1rem then all of a sudden there is a huge amount of gray background above the text—about as much as there is to the left of the text. I would expect to see only one tenth as much padding on the top as on the left. Why the seemingly odd behavior?

Upvotes: 0

Views: 281

Answers (1)

showdev
showdev

Reputation: 29168

I believe this is due to "margin collapse". According to the MDN:

If there is no border, padding, inline content, or clearance to separate the margin-top of a block with the margin-top of its first child block, or no border, padding, inline content, height, min-height, or max-height to separate the margin-bottom of a block with the margin-bottom of its last child, then those margins collapse. The collapsed margin ends up outside the parent.

Your <p> tag has top and bottom margins by default. The margins will collapse and will appear outside of the <div>. But if you add top-padding to the <div>, then the <p> margins no longer collapse and appear inside the <div>.

You can get rid of the <p> margins like so:

p {
  margin:0;
}

Upvotes: 6

Related Questions