Skip to content
Latest: Publish JavaScript Packages to NPM Like a Pro!

CSS Box Model – Explained with Examples

A CSS box model consists of some set of boxes wrapped around an HTML element for styling purposes.

The four (4) boxes that make up a CSS box model are:

  • Margin box
  • Border box
  • Padding box
  • Content box

Here’s an illustration:

Anatomy of a CSS box
model

CSS box model comprises of four boxes

The four boxes that make up a box model make it easy to create complex designs with CSS. Let’s discuss these boxes below.

A content box is the innermost part of a box model. It is where an HTML element’s content appears.

A padding box is a transparent space around the content of a box model.

We use padding to separate the box model’s content from its border.

A border box is a strip of line that typically wraps the padding. But suppose you omit the padding. In that case, the border will wrap the content.

We use the CSS border property to specify the width, color, and style of an HTML element’s border.

A margin box is the transparent outermost edge of a box model.

The main function of a margin box is to separate a box model from other box models.

Example: A <div> Element’s Box Model Demonstration

Section titled “Example: A <div> Element’s Box Model Demonstration”
div {
margin: 50px;
border: 20px solid purple;
padding: 10px;
background-color: orange;
width: 200px;
height: 150px;
}

Try it on StackBlitz

The snippet above specified three properties that we have not discussed: background-color, width, and height—so, let’s talk about them below.

A CSS background-color property defines the color of an HTML element’s background.

A CSS width property defines the width of an HTML element.

A CSS height property defines the height of an HTML element.

Important Stuff to Know about the width and height Properties

Section titled “Important Stuff to Know about the width and height Properties”

By default, the CSS width and height properties set the content box’s width and height.

But suppose you want the width and height properties to refer to an HTML element’s border—not its content. In that case, set the box-sizing property’s value to border-box.

Example: box-sizing Configured to Make the width and height Reference the Border Box

Section titled “Example: box-sizing Configured to Make the width and height Reference the Border Box”
#first-div {
margin: 25px;
border: 17px solid rgba(0, 0, 0, 0.75);
padding: 30px;
background: PeachPuff
url("https://cdn.pixabay.com/photo/2012/04/01/16/39/turkey-23437_1280.png")
center/contain no-repeat padding-box border-box local;
width: 400px;
height: 300px;
box-sizing: border-box;
}

Try it on StackBlitz

The background property is a shorthand for the following properties: