Colours
color: red; /* name */
color: #2563eb; /* hex */
color: rgb(37, 99, 235); /* rgb */
color: hsl(221, 83%, 53%); /* hsl */
background: rgba(0, 0, 0, 0.5); /* with transparency */Units
| Unit | Meaning |
|---|---|
px | Fixed pixels |
% | Percent of the parent |
em | Relative to the element's font size |
rem | Relative to the root font size (best for text) |
vw, vh | Percent of viewport width or height |
The box model
Every element is a box made of four layers, from inside to outside: content, padding, border and margin.
<style>
.box {
width: 200px;
padding: 20px;
border: 4px solid #2563eb;
margin: 30px;
background: #eff6ff;
box-sizing: border-box;
}
</style>
<div class="box">Box model demo</div>- Padding is space inside the border.
- Margin is space outside the border.
- With
box-sizing: border-box, width includes padding and border, which makes layouts much easier. Most developers set it for every element:
*, *::before, *::after { box-sizing: border-box; }Shorthand
margin: 10px 20px 30px 40px; /* top right bottom left */
padding: 10px 20px; /* vertical horizontal */Margin collapsing and centring
Vertical margins between block elements can collapse: when a paragraph with margin-bottom: 20px sits above one with margin-top: 30px, the gap is 30px, not 50px. Horizontal margins never collapse.
To centre a block horizontally, give it a width and set the side margins to auto:
.container { max-width: 900px; margin: 0 auto; }Borders, outlines and rounded corners
.card { border: 1px solid #e5e7eb; border-radius: 12px; }
.avatar { border-radius: 50%; } /* a circle when width equals height */
button:focus { outline: 3px solid #93c5fd; outline-offset: 2px; }An outline is drawn outside the border and does not change the layout. Never remove focus outlines without giving keyboard users another clear focus style.
Inspect it in your browser
Right-click any element and choose Inspect. The browser shows its box model diagram with the exact content, padding, border and margin sizes. This is the fastest way to debug spacing problems.
Practice
Create a card 300px wide with padding, a border, rounded corners using border-radius and a light shadow using box-shadow: 0 4px 12px rgba(0,0,0,0.1);.
Practice tasks
Reading is not enough. Try these without copying code, then compare with the lesson.
- Set width, padding, border and margin on a box and draw its box model on paper.
- Use box-sizing: border-box and compare the widths.
- Use rem, em and px for font sizes and observe the difference when changing the browser font size.
Common mistakes
- Forgetting that padding and border add to the width by default.
- Using px for everything, which ignores user font settings.
Quick check
What is the box model?
Content, padding, border and margin around every element.
What does border-box change?
Width includes the padding and border.