Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Small padding, big difference

Tags:

html

css

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.

like image 921
Daniel Avatar asked Mar 21 '14 15:03

Daniel


People also ask

Is it better to use padding or margin?

In general, use margins when you're adjusting the spacing of an element in relation to another element (i.e a div in relation to another div on the page), and padding when you're adjusting the look of an individual element (i.e the amount of pixels between the edge of a div and the text within it).

Should I use width or padding?

It is normally better to use padding since the button will support different text lengths and let the padding control the width and height depending on the text within the button, However if you want your buttons to be one size and one size only for example: A button with Submit, and a button with Download will be 2 ...

What is padding in spacing?

Padding is the space that's inside the element between the element and the border. Padding goes around all four sides of the content and you can target and change the padding for each side (just like a margin).

Why do we use padding?

Padding is used to create space around an element's content, inside of any defined borders.


1 Answers

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.

like image 88
Fabrizio Calderan Avatar answered Sep 18 '22 14:09

Fabrizio Calderan