….
🎨 CSS Padding — GoNimbus Guide
Padding in CSS controls the space between an element’s content and its border. Think of it as the “breathing room” inside an element.
Unlike margins, which create space outside an element, padding works inside the element’s box, pushing the content inward.
🔹 Padding on Individual Sides
CSS lets you set padding for each side of an element separately:
padding-top
→ space above the contentpadding-right
→ space on the right sidepadding-bottom
→ space below the contentpadding-left
→ space on the left side
✅ Allowed values:
- Length units (px, em, rem, etc.)
- Percentages (relative to container width)
- inherit (copies parent’s padding)
⚠️ Unlike margins, negative padding is not allowed.
Example:
div {
padding-top: 40px;
padding-right: 20px;
padding-bottom: 40px;
padding-left: 60px;
}
🔹 Shorthand Padding Property
You can simplify your code with the padding
shorthand:
- Four values:
padding: top right bottom left;
- Three values:
padding: top right/left bottom;
- Two values:
padding: top/bottom right/left;
- One value: applies the same padding to all sides.
Examples:
div {
padding: 20px 40px 60px 80px; /* 4 values */
}
section {
padding: 10px 25px 50px; /* 3 values */
}
p {
padding: 15px 30px; /* 2 values */
}
button {
padding: 12px; /* 1 value */
}
🔹 Padding and the Box Model
By default, the width property applies only to the content box. Padding adds extra space to the total element size.
Example:
div {
width: 300px;
padding: 25px;
}
📌 Actual element width = 300px + 25px (left) + 25px (right) = 350px
🔹 The box-sizing
Fix
To avoid unexpected sizing, use:
div {
width: 300px;
padding: 25px;
box-sizing: border-box;
}
With box-sizing: border-box
, the total width stays 300px, and padding shrinks the content area instead of expanding the box.
👉 This is a best practice in modern web design and is often applied globally:
* {
box-sizing: border-box;
}
🔹 Practical Use Cases
- Button Styling
button {
padding: 10px 20px;
border-radius: 5px;
}
Gives clickable buttons extra breathing room.
- Responsive Layouts
.container {
padding: 5%;
}
Percentage-based padding adapts to screen size.
- Clickable Areas
a {
padding: 10px;
display: inline-block;
}
Improves accessibility by increasing hit areas on links.
🧩 Exercise
Question:
If a div
has width: 400px; padding: 20px; box-sizing: content-box;
, what is its total rendered width?
- 400px
- 420px
- 440px
- 480px
✔ Correct Answer: 440px (400 + 20 + 20)
📋 Quick Reference
Property | Description |
---|---|
padding | Shorthand for all sides |
padding-top | Sets top padding |
padding-right | Sets right padding |
padding-bottom | Sets bottom padding |
padding-left | Sets left padding |
💡 GoNimbus Tip:
Always combine padding
with box-sizing: border-box;
for predictable layouts. This avoids layout shifts and ensures your designs remain consistent across different devices.