CSSLesson 3 of 10Jump to practice
The box model
Every element is a box. Understand content, padding, border and margin, and how they add up.
To CSS, every element on the page is a rectangle. That rectangle has four layers, from the inside out:
- Content: the text or image itself.
- Padding: space between the content and the border.
- Border: a line around the padding.
- Margin: space outside the border, pushing other elements away.
<!DOCTYPE html>
<html>
<head>
<style>
.box {
background: #cfeee9; /* shows content + padding */
padding: 20px;
border: 6px solid teal;
margin: 30px;
}
</style>
</head>
<body>
<div class="box">Change padding, border and margin, then Run.</div>
</body>
</html>Setting each side
padding and margin accept one to four values:
| You write | It means |
|---|---|
padding: 10px; |
10px on all four sides |
padding: 10px 20px; |
10px top and bottom, 20px left and right |
padding: 5px 10px 15px 20px; |
Top, right, bottom, left (clockwise from the top) |
You can also set a single side with padding-top, margin-left and so on.
Make width behave: box-sizing
By default, width sets only the content. Padding and border are then added on top, so a width: 200px box with 20px padding is really 248px wide. That surprises everyone.
Most developers switch this off at the top of every stylesheet:
* {
box-sizing: border-box;
}
Now width includes padding and border, and a 200px box is 200px.
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 200px;
padding: 20px;
border: 4px solid teal;
margin-bottom: 12px;
background: #eef;
}
.border-box { box-sizing: border-box; }
</style>
</head>
<body>
<div>content-box: wider than 200px</div>
<div class="border-box">border-box: exactly 200px</div>
</body>
</html>Practice
Check what you just learned. Fill in the missing code, then answer the quiz.
Exercise 1Solved
Add 20px of space inside the box, between the text and the border.
.card { : 20px; border: 1px solid gray; }Exercise 2Solved
Add 30px of space outside the border, pushing other elements away.
.card { border: 1px solid gray; : 30px; }Exercise 3Solved
Make
widthinclude padding and border for every element.* { box-sizing: ; }The value names the outermost layer that
widthshould include.
Finish the practice to complete this lesson.
Sign in to keep your progress on any device.