Daniel
Daniel

Reputation: 3711

Small padding, big difference

If I only add a 1px padding to a div around a heading, then this makes apparently a huge difference (http://jsfiddle.net/68LgP/).

html:

<div class="pad0">
    <h1>Text</h1>
</div>
<div class="pad1">
    <h1>Text</h1>
</div>

css:

.pad0 {
    background-color: #E9E9E9;
    padding: 0px;
}
.pad1 {
    background-color: #E9E9E9;
    padding: 1px;
}

Why is that so? I really would like to achieve a similar effect to the 1px padding but with no extra padding added.

Upvotes: 8

Views: 3664

Answers (7)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123428

This is due to the 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.

You can find further information also on w3c site.

Two margins are adjoining if and only if [...] no line boxes, no clearance, no padding and no border separate them [...]

So if you apply a padding-top (1px is enough), as in your second example, the margins are no longer collapsed. An easy solution, as already suggested, is to remove the default margin of your heading elements and apply a padding instead.

Upvotes: 9

rolory
rolory

Reputation: 362

You could use CSS Reset which resets all CSS settings, including this kind of problems. Recommended for any site.
How can CSS Reset file solve your problem? As you can see, in the first paragraph, h1 is included, and it's given margin:0 which is needed for reducing the difference in problems like yours.

Upvotes: 0

Dr R Dizzle
Dr R Dizzle

Reputation: 272

<div> is a block element, which means that it both starts and ends with a line break. I beleive that this is contributing to your problem - you may want to swap to <span> tags, although I'm not sure if this will solve the problem.

Upvotes: 0

Priit
Priit

Reputation: 31

It's to do with the default CSS applied to Heading1 element. It already has a padding/margin applied to it.

If you reset it, you can see the result you're after: http://jsfiddle.net/68LgP/8/.

h1 { padding: 0; margin: 0; }
.pad0 {
    background-color: #E9E9E9;
    padding: 0px;
}
.pad1 {
    background-color: #E9E9E9;
    padding: 1px;
}

Upvotes: 2

Umair Hafeez
Umair Hafeez

Reputation: 407

Please see the updated CSS here

.pad0 {
    background-color: #E9E9E9;
    padding: 0px;
    margin: 0px;
}
.pad1 {
    background-color: #E9E9E9;
    padding: 1px;
    margin: 0px;
}

h1
{
    padding: 0px;
    margin: 0px;
}

Upvotes: 1

James King
James King

Reputation: 1917

It is now keeping the margin of the h1 within the DIV. The h1 has default top and bottom margin of around 21px, so when you add 1px padding to the DIV, it now looks like 22px

Upvotes: 0

Farnabaz
Farnabaz

Reputation: 4066

set h1 margin to 0

h1 {
    margin: 0;
}

Upvotes: 0

Related Questions