The CSS Box Model

The CSS box model represents the space taken up by an HTML element on a webpage. There are 4 components of the box model, which I like to remember with the acronym “MacBook Pro Computer”:

  • Margin
  • Border
  • Padding
  • Content

Every HTML element on a webpage can be thought of as a box, no matter how complex. Take a look the New York Times’ T Magazine webpage:

This row of article images/headlines is a box.

The area containing each article’s image and headline is a box.

You guessed it, this article title is a box too.

In the screenshots above, you’ll notice some different colors in the box. In the Chrome Developer Tools, blue is the content area, green is the padding, and orange is the margin. There aren’t any borders visible here, but they’d be colored yellow.

The CSS box model as the Chrome Developer Tools displays it.

Going from the inside to the edge of the box model, here’s a rundown of what each component of the box model does:

Content is just that, the main content: some text, an image, a video, or something else to display. By default (i.e., without applying the box-sizing CSS property), setting the width and height of an element will set only the width and height for the content box.

Padding is a way of extending the content area. In the example above, adding padding to the box class will “pad” the content, while extending the background color:

Now, the text (content) is padded from the edge by 10 pixels on each side.

Border is the component of the box model that comes after padding, and is self-explanatory. Let’s add a solid-line, black-colored border 3 pixels wide to the box:

There is now a problem in that I have defined the box as being 100px wide and 100px in height via the box class, but the actual width and height of the box is 122px (100px content + 10px padding on each side + 1px border on each side). This is because by default, the width and height properties only affect the content area. To ensure that the box is 100px on both sides, even with the padding and border, I’ll use the box-sizing CSS property.

Now, regardless of the padding and border, the box will be 100px square. The content area is 78px.

Finally, the Margin is the area that “pads” or separates elements that would otherwise touch the box. I’ll add some text just outside the box:

To make the text (or another element) appear a little further from the box, I can add the margin property:

The text is now shifted away from the box due to the margin: