The Box Model
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 every HTML element. It consists of: margins, borders, padding, and the actual content.
1. Parts of the Box Model
- Content: The content of the box, where text and images appear.
- Padding: Clears an area around the content. The padding is transparent.
- Border: A border that goes around the padding and content.
- Margin: Clears an area outside the border. The margin is transparent.
div {
width: 300px;
border: 15px solid green;
padding: 50px;
margin: 20px;
}
2. Width and Height Calculation
By default, in the standard box model, when you set the width and height properties of an element, you are only setting the width and height of the content area. To calculate the full size of the element, you must add padding, borders and margins.
Total Element Width = width + left padding + right padding + left border + right border + left margin + right margin
3. box-sizing Property
The box-sizing property allows you to define how the width and height of an element are calculated: should they include padding and borders, or not?
content-box (Default)
The width and height properties (and min/max properties) includes only the content. Border and padding are not included.
.box {
box-sizing: content-box;
width: 300px;
padding: 20px;
border: 5px solid black;
}
/* Actual rendered width: 300 + 20*2 + 5*2 = 350px */
border-box
The width and height properties (and min/max properties) includes content, padding and border. This makes it much easier to size elements.
.box {
box-sizing: border-box;
width: 300px;
padding: 20px;
border: 5px solid black;
}
/* Actual rendered width: 300px */
/* Content width becomes: 300 - 40 - 10 = 250px */
Best Practice: Many developers apply box-sizing: border-box to all elements for easier layout management.
* {
box-sizing: border-box;
}