🎨 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 content
  • padding-right → space on the right side
  • padding-bottom → space below the content
  • padding-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

  1. Button Styling
button {
  padding: 10px 20px; 
  border-radius: 5px;
}

Gives clickable buttons extra breathing room.

  1. Responsive Layouts
.container {
  padding: 5%;
}

Percentage-based padding adapts to screen size.

  1. 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

PropertyDescription
paddingShorthand for all sides
padding-topSets top padding
padding-rightSets right padding
padding-bottomSets bottom padding
padding-leftSets 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.


Scroll to Top