The CSS Padding Properties

The CSS padding properties are used to control the space between the borders and content of an element.

Edited: 2016-10-04 18:11

The padding properties are used to control the space inside an element, within the edges or borders of the element.

Sometimes it may be better to use padding on certain elements rather than margin, this is because top and bottom margins may collapse. For example, if you set a margin of 1em on the top and 2em on the bottom of paragraphs, you will end up with a space between the elements of 2em rather than the – usually – intuitively expected 3em.

Unlike with margin, the values of padding can not be negative.

All four sides can either be controlled trough the shorthand, or trough the properties used to target each side individually.:

In addition, it is also possible to leave out some of the element sides, if you do this, the value from the other side will be used. I.e.

p {
padding: 1em 0.5em; /* top right bottom left */
}

The above also sets all four borders. The top and bottom share the 1em padding, and the left and right share the 0.5em padding.

Use padding when:

You want the space you are creating to be within an elements borders or edges.

You do not want the background to be "pushed" by the added space.

You want to avoid collapsing margins on paragraphs.

Other than the above it often just comes down to personal preference whether to use margin or padding, but as a rule of thumb, if one does not accomplish what you want, it may be worth your time to experiment a little.