CSS PADDING AND BOX-SIZING

CSS Padding & Box Sizing

1. padding

Padding is the space inside an element, between its content and its border.

.box {
  padding: 20px;
}

This adds 20px of space on all four sides.

You can also specify sides individually:

.box {
  padding-top: 10px;
  padding-right: 20px;
  padding-bottom: 10px;
  padding-left: 20px;
}

Or use shorthand:

padding: 10px 20px;

Meaning:

  • 10px → top & bottom
  • 20px → left & right

2. box-sizing

box-sizing controls how the width and height of an element are calculated.

There are two common values:

box-sizing: content-box;

This is the default.

If:

.box {
  width: 200px;
  padding: 20px;
}

The actual width becomes:

200px + 20px + 20px = 240px

Width:

box-sizing: border-box;

the padding is included inside the specified width:

.box {
  width: 200px;
  padding: 20px;
  box-sizing: border-box;
}

Now the total width is 200px.

Common best practice

Many developers use:

* {
  box-sizing: border-box;
}

This makes layouts easier to control because width and height include the element's content + padding + border.

Easy way to remember:

padding = space inside the box
box-sizing = how the box's size is calculated

Comments