CSS Padding
CSS Padding
CSS padding is used to create space inside elements. Padding adds space between the element’s content and its border.
Padding increases the visible size of an element unless box sizing is adjusted.
Padding
The padding property can be used to set space on all four sides of an element.
.box {
padding: 20px;
}
You can also define padding for each side individually:
.box {
padding-top: 10px;
padding-right: 20px;
padding-bottom: 30px;
padding-left: 40px;
}
Padding Shorthand
Padding shorthand allows you to define multiple sides in one line.
/* top right bottom left */
.box {
padding: 10px 20px 30px 40px;
}
/* top-bottom left-right */
.box {
padding: 20px 40px;
}
Padding and Element Size
By default, padding increases the total size of an element. This can affect layouts if not handled carefully.
.box {
width: 300px;
padding: 20px;
}
The element above will be wider than 300px because padding is added to the width.
Padding and box-sizing
The box-sizing property changes how width and height are calculated.
When box-sizing: border-box is used, padding and border are included inside the defined width.
.box {
width: 300px;
padding: 20px;
box-sizing: border-box;
}
With this setting, the total width remains 300px.
Using box-sizing Globally
A common best practice is to apply box-sizing: border-box to all elements.
* {
box-sizing: border-box;
}
Code Challenge
Goal: Use padding to improve the layout of the card below.
HTML:
<div class="card"> <h3>Padding Example</h3> <p>This card uses padding for spacing.</p> </div>
Task:
- Add padding inside the card
- Keep the card width fixed
- Use
box-sizingto prevent layout issues
Try a Solution:
.card {
width: 400px;
padding: 20px;
box-sizing: border-box;
border: 1px solid #ddd;
border-radius: 12px;
}
What’s Next?
Next, you will learn how margins, borders, and padding work together in the CSS box model.