CSS Box Model

The CSS Box Model is the basis of all layout control for our web pages. It is very simple to understand and use, and yet can be incredibly powerful, allowing us to position and space our HTML elements exactly as we want.

There are four elements to the Box Model. The first is our content, such as our text or an image. Around this content we have the padding. This defines the space between our content and the edge of the element. Next we have the border element which we can use to draw a line around our content. Finally there is the margin, which defines the gap between the edge of the element and any other elements on the page. This may all sound a little confusing so let's have a look at a visual example:

CSS box model

In this example we have surrounded the content with 20px of padding, followed by a 1px solid black border, and finally a 20px margin. Each element has been colored differently for clarity; in reality the padding is colored the same as the content background color and the margin is invisible. Borders are optional and you will probably use them relatively rarely, but they can be useful in many circumstances, such as putting a border around our images.

How to use padding, borders, and margins

We can assign padding, borders and margins to any one of our HTML elements using CSS. The commands are really very simple. For example, assume we want to put 1em of padding, followed by a 2px solid green border, followed by a 2em margin, around each of our <h2> headings. We would code this as follows:

h2 {
	padding: 1em;
	border: 2px solid green;
	margin: 2em;

That's all there is to it! By adding just three simple lines of code we can easily make significant layout changes to any of the HTML elements within our web pages.

So far we have used equal thicknesses for our padding, border, and margin on all sides. In the next section we will see how we can set individual values for each side to give us even more control over our layout.