The CSS padding box is the space between the content of an element and its border. The padding
property is a shorthand for setting the padding on all four sides of an element at once, or you can use individual properties like padding-top
, padding-right
, padding-bottom
, and padding-left
.
Example 1: Uniform Padding
.box {
/* Sets a 20-pixel padding on all four sides */
padding: 20px;
background-color: #f0f0f0;
border: 1px solid #ccc;
}
Explanation
This code applies a uniform padding of 20 pixels to all four sides of any element with the class "box". This is the simplest way to add equal spacing around your content.
Example 2: Vertical and Horizontal Padding
.box {
/* Sets 15px padding for top/bottom and 30px for left/right */
padding: 15px 30px;
background-color: #e6f7ff;
border: 1px solid #91d5ff;
}
Explanation
When two values are provided, the first value sets the padding for the top and bottom, and the second value sets the padding for the left and right sides of the element.
Example 3: Individual Side Padding
.box {
/* Sets padding for top, right, bottom, and left individually */
padding: 10px 20px 30px 40px;
background-color: #fffbe6;
border: 1px solid #ffe58f;
}
Explanation
Using four values with the padding
property allows you to set the padding for the top, right, bottom, and left sides in that specific clockwise order.
Example 4: Using Different Units
.box {
/* Sets top padding in em, right/left in percentage, and bottom in vw */
padding: 1em 5% 2vw;
background-color: #f6ffed;
border: 1px solid #b7eb8f;
}
Explanation
This example uses three values: the first for the top (1em
), the second for the left and right (5%
), and the third for the bottom (2vw
). CSS padding allows for various units, making it flexible for responsive designs.
Example 5: Using padding-left
.box {
/* Specifically adds 50 pixels of padding to the left side */
padding-left: 50px;
background-color: #e6f7ff;
border: 1px solid #91d5ff;
}
Explanation
The padding-left
property isolates and applies padding only to the left side of the element, leaving the other three sides unaffected unless specified otherwise.
Example 6: Using padding-bottom
.box {
/* Specifically adds 2rem of padding to the bottom */
padding-bottom: 2rem;
background-color: #fff0f6;
border: 1px solid #ffadd2;
}
Explanation
The padding-bottom
property is useful for adding space below the content within its border. Here, we use the rem
unit, which is relative to the root font size.
Example 7: Combining Shorthand and Individual Properties
.box {
/* Sets a base padding for all sides */
padding: 20px;
/* Overrides the top padding specifically */
padding-top: 5px;
background-color: #f9f0ff;
border: 1px solid #d3adf7;
}
Explanation
In this code, a general padding of 20px is set first. Then, the padding-top
is overridden to be 5px. This demonstrates how you can set a baseline and then adjust a specific side.