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:

  1. Content: the text or image itself.
  2. Padding: space between the content and the border.
  3. Border: a line around the padding.
  4. Margin: space outside the border, pushing other elements away.
The four layers
Open in editor
<!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>
Result

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.

content-box vs border-box
Open in editor
<!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>
Result

Practice

Check what you just learned. Fill in the missing code, then answer the quiz.

  1. Exercise 1

    Add 20px of space inside the box, between the text and the border.

    .card {
      : 20px;
      border: 1px solid gray;
    }

  2. Exercise 2

    Add 30px of space outside the border, pushing other elements away.

    .card {
      border: 1px solid gray;
      : 30px;
    }

  3. Exercise 3

    Make width include padding and border for every element.

    * {
      box-sizing: ;
    }

Quiz: 3 questions

1. Put the box model layers in order from the inside out.
2. What does padding: 10px 20px; mean?
3. Without box-sizing: border-box, a box has width: 200px, padding: 10px and a 5px border. How wide is it on screen?

Finish the practice to complete this lesson.