Spacing — Margin and Padding
Spacing is what separates a page that feels cramped from one that breathes. CSS gives you two properties for it — padding and margin — and the difference between them is one of the most important things to understand in CSS.
The box model
Every HTML element is a box. Around the content, there are layers:
┌──────────────────────────────────┐
│ margin │ ← space outside the element
│ ┌──────────────────────────┐ │
│ │ border │ │
│ │ ┌──────────────────┐ │ │
│ │ │ padding │ │ │ ← space inside the element
│ │ │ ┌──────────┐ │ │ │
│ │ │ │ content │ │ │ │
│ │ │ └──────────┘ │ │ │
│ │ └──────────────────┘ │ │
│ └──────────────────────────┘ │
└──────────────────────────────────┘
- Padding — space between the content and the border. Inside the element. Background colour fills it.
- Margin — space between the element and everything around it. Outside the element. Always transparent.
padding
Adds breathing room inside an element. Useful on buttons, cards, and content sections:
button {
padding: 10px 20px;
}
10px 20px means: 10px top and bottom, 20px left and right.
You can set all four sides individually:
.card {
padding-top: 20px;
padding-right: 16px;
padding-bottom: 20px;
padding-left: 16px;
}
Or all four in one shorthand line (top, right, bottom, left — clockwise from the top):
.card {
padding: 20px 16px 20px 16px;
}
margin
Adds space around an element — pushes it away from its neighbours.
h1 {
margin-bottom: 8px;
}
p {
margin-bottom: 16px;
}
A very common trick — centering a block element horizontally on the page:
.container {
width: 800px;
margin: 0 auto;
}
margin: 0 auto means zero top and bottom, automatic left and right — which splits the remaining space equally and centres the element.
Seeing the difference
Add this to a page and compare:
.box-padding {
background-color: lightblue;
padding: 30px;
}
.box-margin {
background-color: lightcoral;
margin: 30px;
}
With padding: the background colour expands with the space — the padding is inside.
With margin: the background stays tight to the content — the space is outside.
That difference becomes obvious immediately when you see it in the browser.
Challenge
Update style.css for your portfolio.html:
- Add
padding: 20pxtobody— notice how the content no longer touches the edges - Add
margin-bottom: 12pxto yourpelements — see the space between paragraphs - Create a class called
.sectionwithpadding: 24pxand a background colour - Apply
class="section"to one of your content areas
Compare the page before and after. Spacing alone changes the feel of the whole page.