CSS Padding
CSS padding is used to create space between the content of an HTML element and its border.
Padding is inside the element. It makes the content more comfortable to read and prevents the content from touching the border directly.
Basic Syntax
selector {
padding: value;
}
Padding Diagram
Simple Explanation
Think of padding as the inner space of an element.
If your content is directly touching the border, the design can look crowded.
By adding padding, you create space between the content and the border.
Padding is inside the border. Margin, which you will learn next, is outside the border.
Example 1: Basic Padding
The following example adds 20px of padding on all four sides of the element.
.box {
background-color: lightblue;
border: 2px solid blue;
padding: 20px;
}
Output
Example 2: Padding on Individual Sides
CSS allows you to control padding separately for the top, right, bottom, and left sides.
.box {
background-color: lightgreen;
border: 2px solid green;
padding-top: 10px;
padding-right: 20px;
padding-bottom: 30px;
padding-left: 40px;
}
Output
Different padding values are applied to each side.
Example 3: Padding Shorthand
Instead of writing four separate properties, you can use the padding shorthand property.
.box {
background-color: lightyellow;
border: 2px solid orange;
padding: 10px 20px 30px 40px;
}
Output
Padding shorthand controls all four sides.
Padding Shorthand Rule
When four values are provided, CSS follows the clockwise direction:
10px
20px
30px
40px
padding: 10px 20px 30px 40px;
/*
Top = 10px
Right = 20px
Bottom = 30px
Left = 40px
*/
Two-Value Padding
When two values are used, the first value applies to the top and bottom, while the second value applies to the left and right.
.box {
background-color: #e9d5ff;
border: 2px solid purple;
padding: 15px 30px;
}
Output
Padding Properties
padding-top
Controls the space between the content and the top border.
padding-right
Controls the space between the content and the right border.
padding-bottom
Controls the space between the content and the bottom border.
padding-left
Controls the space between the content and the left border.
Padding vs Margin
| Padding | Margin |
|---|---|
| Space inside the border. | Space outside the border. |
| Creates space around content. | Creates space between elements. |
| Part of the element's box. | Outside the element's box. |
Summary
CSS padding creates space between an element's content and its border. Padding can be applied to all four sides using the shorthand property or controlled individually using padding-top, padding-right, padding-bottom, and padding-left. Remember: padding is inside the border, while margin creates space outside the border.