Unit 3 · CSS: the look and the layout
Margin vs padding in CSS
Padding is space inside the border, between the content and the edge, and it shows the box’s background colour. Margin is space outside the border that pushes other boxes away and is always transparent.
The mix-up
What people often think
“Margin and padding are two words for the same space.”
What the tutor says
Padding is space inside the border, so it shares the background colour. Margin is space outside the border that pushes other boxes away.
If you gave this box a red background, which ring would turn red: padding or margin?
How it works
Every box is a set of rings, always in the same order from the inside out: content, padding, border, margin. The border is the line between the inside space and the outside space.
A quick test: give the box a red background. The padding turns red; the margin does not. Use padding to give text room to breathe inside a card, and margin to separate one card from the next.
An example
.card {
padding: 16px; /* inside: text away from the edge */
border: 2px solid #ccc;
margin-bottom: 24px; /* outside: space before the next card */
background: #fff;
}Close cousins of this mix-up
The tutor watches for these in the same lesson.
“Margin is the space inside the box and padding is outside.”
It is the other way round. Padding sits inside the border, next to the text. Margin sits outside, between this card and the next one.
“The rings can go in any order.”
The order is always the same, from the inside out: content, padding, border, margin. The border is the line between the inside space and the outside space.
Practise it with a tutor watching
The box model
Predict exactly how much space a box takes, and size it with padding, border and margin.
Free, no account needed.