CSS Box Model

The CSS Box Model is the foundation to control all of the layout elements of your web pages.

Even though the concept of the box is simple, it is undeniably the most robust platform for manipulating the positions and space of the HTML elements the way you desire.

For a more practical understanding, when you create a document, each element of your document will appear as a rectangular box within the standard dictated by the CSS box model.

The large box has four components which are:

  • Content
  • Padding
  • Border
  • Margin

Visually, this is what we mean:

CSS Box Model Visual

 

1. Content

Elements in this area would include text, images or videos that you want to present to users.
 

2. Padding

The padding is an extension element used to increase the area around your content.

 

3. Border

The border, in turn, extends the area of the padding to include elements such as borders. The thickness of the edges is subject to manipulation.

 

4. Margin

The margin area then goes on to extend the border area. The extension allows the inclusion of an empty region that is used to separate two adjoining elements.

 

So now the question is, how do I use padding, borders, and margins?

The CSS box model enables you to apply padding, borders, and margins to any number of HTML elements present on your web page.

For example:

h2 {
padding: 2em;
border: 3px solid blue
margin: 3em;
}

Yes, it’s that simple!

A few lines of code can help make a big difference in terms of spacing and layout.

The box model is the core to how CSS is structured so it’s important to understand it before continuing.

 

Different Values for each side of Padding & Margin

In the above example, the padding, border and margin values we set are equally applied to all 4 sides of the web page.

However, what if you only want padding on the left and right side and not the top and bottom?

That’s where suffixes like -left, -right, -top and -bottom can be added to the style declarations to control an individual side.

Suppose you want a margin of 2em at the top and right, 3em on the bottom of your web page, and 1em on the left?

You can set a 2em margin for all borders and then set the left one to the desired value of 1em.

Example:

img
{
margin: 2em;
margin-bottom: 3em;
margin-left: 1em;
}

There is a simple shorthand version of these properties, and it follows a clockwise pattern around a square box so:

margin: Top, Right, Bottom, Left

So your code in shorthand would look like this:

img
{
margin: 2em; 2em; 3em; 1em;
}

The same approach can be used with the padding element.

To learn more check out apply CSS padding and margin to your entire web page.