Box Model

The box model is a crucial basic component when it comes to learning CSS. It describes how every HTML element is displayed as a box with multiple layers.

Every element has a content box, padding box, border box and margin box. When creating layouts in CSS, knowing whether to use margin or padding for spacing makes a large difference.

These boxes surround each other: the margin box surrounds the border box, the border box surrounds the padding box, and the padding box surrounds the content box. The image below may help you get a visual sense of the box model.

Simply put, it’s just a bunch of layers on a box.

Content

The content box is where the real content of the element exists. This content is usually text, images or videos.

This is where the content is located in this playground.

Padding

Padding surrounds the content, allowing you to add more spacing between the content and the border, or from other elements.

Here is where the padding box is positioned in this playground. The padding section adds a bit more spacing between the content and the border (which is covered later).

Below is a widget to play around with the padding of all 4 sides of the element.

Padding

.item { padding: 20px; }

An alternate syntax can be used to choose the padding of all 4 sides of the element. The 4 values modify the top, right, bottom and left padding sides in that order.

Padding

.item { padding: 20px 20px 20px 20px; }

Border

Borders are placed between the padding and margin. They’re usually used visually separate content from other content with a border.

Here is where the border box is positioned in this playground.

Borders have 3 specific components: border-width, border-type and border-color. The widget below allows you to play around with all 4 sides of an elements border.

Border

.item { border: 5px dashed #194d33; }

An alternate syntax allows you to individually set the border of a specific side. Valid CSS properties are : border-top, border-right, border-bottom andborder-left.

Border

.item { border-top: 5px dashed #194d33; }

Margin

Margins are positioned outside of the border.

Here is where the margin box is positioned in this playground. In this case, it adds more space between the outside of the element and the border.

Here is a widget to display margins. This syntax sets the margin on all 4 sides of the element.

Margin

.item { margin: 10px; }

An alternate syntax can be used to choose the margin of all 4 sides of the element. The 4 values modify the top, right, bottom and left margin sides in that order.

Margin

.item { margin: 10px 10px 10px 10px; }