Boxes: padding, borders and margins

Every element is a box. Control the space inside and around it.

Your CSS is drawn by your own browser, inside this tab. Nothing to install.

Every element is a box

The browser draws each element as a box. From the inside out it has the content, then padding, then a border, then margin.

padding is space inside the box, between the content and the border. A background colour fills it.

Run the example to see space appear inside the card.

Example
.card {
  background-color: lightyellow;
  padding: 20px;
}

Your turn: space inside

Give the list some room.

Practice task

Give the element with the id menu 30 pixels of padding on every side.

Your answer is run and checked in the lesson. Create a free account to try it.

Borders

border draws a line around the box. It takes three values in one go: a width, a style and a colour.

solid is a plain line. dashed and dotted are the other common styles.

border-radius rounds the corners.

Example
.card {
  border: 2px solid brown;
  border-radius: 8px;
}

Your turn: a border

Three values, separated by spaces.

Practice task

Give the card a solid black border that is 3 pixels wide.

Your answer is run and checked in the lesson. Create a free account to try it.

Margins

margin is space outside the box. It pushes other elements away.

margin-top, margin-right, margin-bottom and margin-left set one side at a time. Padding has the same four.

Example
.card {
  margin-top: 40px;
}

Your turn: space outside

Set one side only.

Practice task

Give the h1 a bottom margin of 50 pixels.

Your answer is run and checked in the lesson. Create a free account to try it.