10. CSS Padding

What you will learn

  • What padding is and how it differs from margin
  • How to set padding on each side
  • How padding affects the size of an element

What is padding?

Padding is the space inside an element, between its content and its border. The element’s background colour fills the padding.

Quick memory aid: margin is space outside the border (keeping others away). Padding is space inside the border (giving content room to breathe).

A first example

Example

<style>
  .tight { background-color: #cfe6ff; border: 2px solid #0d6efd; }
  .roomy { background-color: #cfe6ff; border: 2px solid #0d6efd; padding: 24px; }
</style>

<p class="tight">No padding</p>
<p class="roomy">24px of padding</p>

Output

No padding

24px of padding

Padding on each side

The properties are padding-top, padding-right, padding-bottom, and padding-left. The shorthand works exactly like margin:

Example

<style>
  .btn {
    display: inline-block;
    background-color: #0d6efd;
    color: white;
    padding: 10px 24px;   /* top and bottom 10px, left and right 24px */
    border-radius: 6px;
  }
</style>

<span class="btn">Click me</span>

Output

Click me

Padding adds to the size

By default, an element’s width covers only its content. Padding (and border) are added on top, making the whole box bigger than you may expect.

Example

<style>
  div {
    width: 200px;
    padding: 20px;
    background-color: #cfe6ff;
  }
</style>

<div>Width 200px + 20px padding on each side = 240px wide</div>

The next lessons explain this in full. The box-sizing property can change the behaviour.

Padding cannot be negative

Unlike margins, padding must be zero or positive.

Percentages

A percentage padding is based on the width of the containing block, even for top and bottom padding. For example, padding: 5%; gives roughly the same space on all four sides of a wide container.

Common mistakes

  • Using margin when you want space inside the box, so the background does not extend.
  • Forgetting that padding makes the element wider than its set width.
  • Trying negative padding, which is invalid.
  • Using very small padding on buttons and links, which makes them hard to tap on a phone.

Exercise

Give .note a light yellow background (lightyellow), a 1px solid grey border, and 16px of padding on all sides.

Show solution
<style>
  .note {
    background-color: lightyellow;
    border: 1px solid grey;
    padding: 16px;
  }
</style>
<p class="note">Give me room.</p>

Knowledge check

1. Is padding inside or outside the border?

Inside.

2. Does the background colour fill the padding?

Yes.

3. Can padding be negative?

No.

Summary

  • Padding is space inside an element, around its content.
  • The shorthand matches margin: one to four values.
  • Padding adds to the element’s total size by default.
Scroll to Top