CSS Box Model

What is the box model?

The CSS Box Model. All HTML elements can be considered as boxes. In CSS, the term "box model" is used when talking about design and layout. The CSS box model is essentially a box that wraps around HTML elements, and it consists of: margins, borders, padding, and the actual content.

Wait, what?

A little Syntax, to clear things up

In CSS, there are RULES. Each RULE consists of a SELECTOR, PROPERTIES and their VALUES.

SELECTOR {
    property: value;
}

The selector can be a TAG (DIV, SPAN, P, etc), element ID (#idname) or class

/* Select by tag */
DIV {
    color: blue;
}
/* Select by ID */
#div_id {
    color: blue;
}
/* Select by class */
.div_class {
    color: blue;
}

Margins

The CSS margin properties are used to generate space around elements. The margin properties set the size of the white space OUTSIDE the border.

So what are all those properties you mentioned?

Border

The CSS border properties allow you to specify the style, width, and color of an element's border.

So what are all those properties you mentioned?

Padding

The padding clears an area around the content (inside the border) of an element. The padding is affected by the background color of the element.

So what are all those properties you mentioned?

Element width is calculated by adding width, padding (left+right), and border (left+right).

What does it all mean, when talking about box size?

Element height is calculated by adding height, padding (top+bottom), and border (top+bottom).

.element {
    width: 50px;
    height: 50px;
    margin: 10px;
    padding: 10px;
    border: 2px solid green;
}

Total Width:

50px + 2×10px + 2×2px

= 74px

Margins are not counted in size calculation, but they do matter.

Title Text

Box Model

By lurx

Box Model

  • 47