CSS Tutorial
CSS Padding
Padding creates space INSIDE an element, between its content and its border. It gives your content room to breathe so text does not touch the edges.
What is padding?
Padding is the space between an element's content and its border. Unlike margin, padding is inside the element, so if the element has a background color, the padding area is colored too. This is what stops text from crowding against a box's edge.
Padding on each side
As with margins, you can set each side individually using padding-top, padding-right, padding-bottom and padding-left.
div {
padding-top: 10px;
padding-right: 20px;
padding-bottom: 10px;
padding-left: 20px;
}The padding shorthand
The padding shorthand follows the same clockwise rule as margin: top, right, bottom, left. One value applies to all four sides; two values set top/bottom then left/right.
padding: 20px; /* all sides */
padding: 10px 20px; /* top/bottom | left/right */
padding: 5px 10px 15px 20px;/* top | right | bottom | left */See padding in action
<!DOCTYPE html>
<html>
<head>
<style>
.box {
background-color: #2b5cff;
color: white;
margin: 8px 0;
font-family: Arial, sans-serif;
}
.tight { padding: 4px; }
.roomy { padding: 30px; }
</style>
</head>
<body>
<div class="box tight">Only 4px of padding</div>
<div class="box roomy">A generous 30px of padding</div>
</body>
</html>Padding vs margin
Padding and margin are often confused. Padding is the space inside the border; margin is the space outside it. Padding takes the element's background color; margin is always transparent.
| Padding | Margin | |
|---|---|---|
| Location | Inside the border | Outside the border |
| Background | Takes the element's color | Always transparent |
| Purpose | Space around the content | Space between elements |
| Auto centering | No | Yes (margin: 0 auto) |
Padding is what makes buttons comfortable to click. A button with padding: 10px 20px has a nice clickable area around its text.
By default, padding adds to an element's total width and height. Use box-sizing: border-box if you want the set width to include padding.
Key points
- Padding is space inside the border, around the content.
- It takes the element's background color.
- Set sides individually or with the shorthand.
- Shorthand order is top, right, bottom, left.
- Padding differs from margin, which is outside the border.
