Lesson Wednesday

There's one last major piece of HTML and CSS we need to cover: the box model. Each element on a web page takes up space, and the box model describes the space around the element. Let's start with some unstyled HTML and then add CSS as we go to illustrate the box model:

box-model.html
<!DOCTYPE html>
<html>
  <head>
    <link href="css/styles.css" rel="stylesheet" type="text/css" media="all">
    <title>Box model</title>
  </head>
  <body>
    <div class="my-class">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</div>
  </body>
</html>

Now, let's add a border around this text:

styles.css
.my-class {
  border: 2px solid green;
}

Here's how to increase the space between the text in the <div> and the border around it:

styles.css
.my-class {
  border: 2px solid green;
  padding: 4px;
}

Finally, we might want to make some room between the margin and the elements around it (which are, in this simple case, just the edges of the page):

styles.css
.my-class {
  margin: 12px;
  border: 2px solid green;
  padding: 4px;
}

Now, let's apply a background color to this part of the page:

styles.css
.my-class {
  margin: 12px;
  border: 2px solid green;
  padding: 4px;
  background-color: orange;
}

It just colors the content itself and the padding around it.

The box model is perhaps easiest to understand with a picture:

A diagram of the CSS box model.

You'll run into the box model a lot when building web pages, so it's a good idea to get familiar with it.

Terminology


  • Box model: A model that shows the properties of how the space around an element is assigned and manipulated with CSS.

A diagram of the CSS box model.

Example


.my-class {
  margin: 12px;
  border: 2px solid green;
  padding: 4px;
  background-color: orange;
}