The CSS Box Model

Go back to HTML and CSS Index

What is it?

Every HTML element has it's own little box, and all of these little boxes have some common properties: width, height, padding, border and margin.

The padding property specifies the area inside the border, and margin the area outside.

So what is the CSS box model then? Well, it is a set of rules that defines how every element in a web page is rendered. It has five main parts that determine the size and shape of the box: width, height, padding, border, and margin. The three latter are optional - meaning that we don't need them. The other two, if not given, depend on the content inside the element.

box-sizing: content-box (the standard value)

Be aware that when adding margin and padding, they are added to the width and height of the box, meaning that a box with a width of 100px that has a margin of 20px, a border of 1px, and a padding of 20px will have a total width of: 20px+1px+20px+100px+20px+1px+20px = 182px:

div {
width: 100px;
height: 50px;
padding: 20px;
border: 1px solid black;
margin: 20px;
}
4.1 | box-sizing: content-box (standard value)

Example

Using Google Chrome's Developer Tool (inspect), we can see how it works by scrolling down to the very bottom:

The size of a content box 4.2 | The size of a content-box

box-sizing: border-box

To make all of it a part of the element, use the box-sizing property on the particular box and set the value to border-box:

div {
width: 100px;
height: 50px;
padding: 20px;
border: 1px solid black;
margin: 20px;
box-sizing: border-box;
}
4.3 | box-sizing: border-box

Example

Now the total width of the box is not the margin + the border + the padding + the actual size of the box, it is just the width, meaning 100px:

The size of a border box 4.4 | The size of a border-box

Some web developers prefer to only use the border box, whenever they feel like they need to, to get the correct size. Personally, I always base my layout on border boxes, which is why I always start my CSS documents with these 4 lines of code:

* {
box-sizing: border-box;
margin: 0;
}
4.3 | box-sizing: border-box

This makes every single little box in the page a border box and removes all margins that are otherwise added by the browser, including the white space around the content in the body element that you may or may not have noticed while developing your first pages.

How you choose to go about it, is up to you.

Learn more

Next up

So many boxes, and so many ways to go about it... in the next lesson, we will see an example of how one problem may be solved in three different ways.

Next up: 1 problem, 3 solutions: How to make rounded images