The CSS Padding Properties
The CSS padding properties are used to control the space between the borders and content of an element.
Edited: 2019-09-11 16:29
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.:
div {
padding-top: 1em;
padding-right: 0.5em;
padding-bottom: 2em;
padding-left: 1em;
}
The shorthand equivalent would be:
div {
padding: 1em 0.5em 2em 1em; /* top right bottom left */
}
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.
Properties
Property | Function |
---|---|
padding | The shorthand way to apply padding. |
padding-top | Space from the top edge in an element. |
padding-right | Space from the right edge in an element. |
padding-bottom | Space from the bottom edge in an element. |
padding-left | Space of the left edge in an element. |
Possible Values
- auto (Default)
- Units of Measurement
- initial
- inherit
Inherited? NO!
Tell us what you think: