CSS Padding
CSS padding is used to create space inside an element, between its content and its border. It helps improve readability and layout by controlling the internal spacing of elements.
Padding Property
The padding property sets the inner space for all four sides of an element.
div {
padding: 20px;
}
Individual Padding Sides
You can set padding for each side individually using:
padding-top, padding-right, padding-bottom, and
padding-left.
div {
padding-top: 10px;
padding-right: 15px;
padding-bottom: 10px;
padding-left: 15px;
}
Shorthand Padding Property
The shorthand padding property allows you to set all sides in one line:
/* top right bottom left */
div {
padding: 10px 15px 20px 25px;
}
/* top & bottom, left & right */
div {
padding: 10px 20px;
}
/* all sides same */
div {
padding: 15px;
}
Percentage Padding
Padding can also be set in percentages relative to the parent element's width.
div {
padding: 5%;
}
Best Practices for Padding
- Use consistent padding to create balanced spacing
- Combine padding with margin to structure layouts
- Prefer shorthand
paddingfor cleaner code - Adjust padding for responsive design on different screen sizes
Common Mistakes with Padding
- Using too much padding that breaks layout
- Forgetting to account for box-sizing when adding padding
- Mixing units inconsistently (px, %, em)
Tip: Set
box-sizing: border-box; to include padding within element's total
width and height for easier layout control.