The CSS padding properties let you adjust the space between an element's content and its border (or the edge of the element's box, if there's no border defined).
Padding is influenced by the element's background-color
. For example, if you set a background color for an element, it will be visible through the padding area.
You can set padding for each side of an element separately, like the top, right, bottom, and left sides, using the CSS padding-top
, padding-right
, padding-bottom
, and padding-left
properties. Let's look at an example to see how it works:
h1 {
padding-top: 50px;
padding-bottom: 100px;
}
p {
padding-left: 75px;
padding-right: 75px;
}
You can specify padding values using the following units:
Unlike CSS margin, padding values cannot be negative.
The padding
property is a shorthand method to set padding for all sides at once, instead of setting padding-top
, padding-right
, padding-bottom
, and padding-left
separately.
Here's an example to show how this shorthand property works:
h1 {
padding: 50px; /* apply to all four sides */
}
p {
padding: 25px 75px; /* vertical | horizontal */
}
div {
padding: 25px 50px 75px; /* top | horizontal | bottom */
}
pre {
padding: 25px 50px 75px 100px; /* top | right | bottom | left */
}
This shorthand notation can take one, two, three, or four space-separated values.
Using shorthand properties is recommended as it saves time and makes your CSS code easier to read and maintain.
When designing web layouts, adding padding or borders to elements can sometimes lead to unexpected results. This is because padding and borders are added to the element's width and height, as explained in the CSS box model chapter.
For example, if you set a <div>
element's width to 100% and add left or right padding or borders, a horizontal scrollbar will appear. Here's an example:
div {
width: 100%;
padding: 25px;
}
To prevent padding and borders from changing an element's box width and height, you can use the CSS box-sizing
property. In the following example, the <div>
box's width and height remain the same, but its content area will decrease as padding or border increases.
div {
width: 100%;
padding: 25px;
box-sizing: border-box;
}
You will learn more about the CSS box sizing feature in upcoming chapters.