Put a page together

INPUT · Slides

Space inside and space outside

01 / 05

A box is made of four layers

In CSS every element is treated as the same four layers of box. From the inside out:

  • the contents … the writing or the picture itself
  • padding … the space between the contents and the border
  • border … the border
  • margin … the space outside the border, between this and its neighbour

This way of thinking is called the box model.

02 / 05

padding is the space inside

Add padding and the gap between the border and the writing grows. Picture the box swelling from the inside.

When a box with a background colour or a border looks cramped, padding is the first thing to suspect.

.box {  border: 1px solid #cccccc;  padding: 16px;}

03 / 05

margin is the space outside

Add margin and the gap between this box and the next one opens up. The box keeps its size; only its position moves.

When things you lined up are touching, margin is what you want.

.item {  margin-bottom: 24px;}

04 / 05

Set them side by side

Both take a side name to work on one side only, written like padding-top or margin-left.

With a single value, padding: 16px; means 16px on all four sides.

.box {  padding-top: 24px;  padding-left: 32px;  margin-bottom: 40px;}

05 / 05

margin can put it in the middle

margin also takes the value auto. Write margin: 0 auto; on a box with a width and equal space goes in on the left and right automatically, so it lands in the middle.

The centring you did earlier with inline-block is normally written this way instead. Have a go.

.main {  width: 600px;  margin: 0 auto;}