What is the Box Model?
Every HTML element on a web page is treated as a rectangular box. The CSS Box Model describes how these boxes are constructed and how their dimensions and spacing are calculated. It's essential for controlling the layout and appearance of your web pages.
The box model consists of four main components:
- Content: The actual text, images, or other media within an element.
- Padding: The space between the content and the border. It's transparent.
- Border: A line that goes around the padding and content.
- Margin: The space outside the border, separating the element from other elements. It's transparent.
Think of it like this: Content is the picture, Padding is the mat around the picture, Border is the frame, and Margin is the space between your framed picture and the wall.
Visualizing the Box Model
Let's visualize a simple box with some properties:
/* Example HTML */
<div class="box-visualizer">
<span>Content Area</span>
</div>
/* Example CSS */
.box-visualizer {
width: 200px; /* Content Width */
height: 100px; /* Content Height */
padding: 30px;
border: 5px solid red;
margin: 30px;
background-color: lightblue;
}
The Total Size
The total width of an element is calculated as: width + padding-left + padding-right + border-left + border-right
.
The total height of an element is calculated as: height + padding-top + padding-bottom + border-top + border-bottom
.
This can sometimes lead to unexpected results if you set a width and then add padding and borders. The box-sizing
property can change this behavior.
The `box-sizing` Property
By default, elements use box-sizing: content-box;
. This means the width
and height
properties apply only to the content area. The padding and border are added *outside* of this.
If you set box-sizing: border-box;
, the width
and height
properties include the padding and border. The content area will shrink to make room for them. This is often preferred for easier layout management.
.my-element {
width: 100px;
height: 100px;
padding: 20px;
border: 5px solid green;
background-color: lightgreen;
/* Default: content-box */
/* Total width = 100 + 20 + 20 + 5 + 5 = 150px */
/* Using border-box */
/* box-sizing: border-box; */
/* Total width = 100px (content area shrinks) */
}
Tip: A common practice is to apply box-sizing: border-box;
to all elements using a universal selector:
*, *::before, *::after {
box-sizing: border-box;
}
Interactive Box Model Adjuster
Use the controls below to see how padding, border, and margin affect the visual size of the box. Note how the content size adjusts when box-sizing
is border-box
.