In CSS, padding is the space between an element's content and its border. It is a fundamental property for controlling the layout and spacing of elements on a webpage, ensuring content doesn't sit directly against the container's edge.
Example 1: Padding on all sides
/* This rule applies 20 pixels of padding to all four sides of any <p> element. */
p {
padding: 20px;
}
Explanation
This code adds a uniform 20-pixel space on the top, right, bottom, and left of the paragraph's content, pushing the border outwards.
Example 2: Individual side padding
/* This rule individually sets the padding for each side of the <div> element. */
div {
padding-top: 10px;
padding-right: 20px;
padding-bottom: 15px;
padding-left: 25px;
}
Explanation
This demonstrates how to apply different padding values to each side of an element for more granular control over the internal spacing.
Example 3: Shorthand with four values
/* This shorthand rule applies padding in a clockwise direction: top, right, bottom, left. */
.four-value-box {
padding: 10px 20px 15px 25px;
}
Explanation
This is a more concise way to set all four padding values in a single declaration, following the order: top, right, bottom, and then left.
Example 4: Shorthand with three values
/* This shorthand applies 10px to the top, 20px to the left and right, and 15px to the bottom. */
.three-value-box {
padding: 10px 20px 15px;
}
Explanation
When three values are used, the first sets the top padding, the second sets the left and right padding, and the third sets the bottom padding.
Example 5: Shorthand with two values
/* This shorthand applies 10px to the top and bottom, and 20px to the left and right. */
.two-value-box {
padding: 10px 20px;
}
Explanation
Using two values, the first value is applied to the top and bottom, while the second value is applied to the left and right sides.
Example 6: Padding with different units
/* This rule uses a percentage for horizontal padding and pixels for vertical padding. */
.mixed-units {
padding: 20px 5%;
}
Explanation
This example shows the flexibility of CSS padding by mixing units. The vertical padding is a fixed 20 pixels, while the horizontal padding is a responsive 5% of the containing element's width.
Example 7: The padding-inline
logical property
/* This logical property applies padding to the start and end of the element in its writing mode. */
.logical-padding {
padding-inline: 30px;
}
Explanation
Logical properties like padding-inline
are useful for multi-lingual sites. In a left-to-right language, this applies padding to the left and right. In a right-to-left language, it would still correctly apply to the left and right.