The CSS Box Model is the most fundamental concept in web design. Every single element on a webpage is considered a rectangular box. Even if an element looks circular (like a rounded button), the browser still calculates its position and size as a box. Every box consists of four parts: content, padding, borders and margins.
Understanding how these boxes are structured is the key to mastering layout and spacing.
The Parts of the Box Model
The box model consists of four distinct layers that wrap around your content. Moving from the inside out, they are:
- Content: The actual text, images, or video. This is where the width and height properties usually apply.
- Padding: The clear area around the content but inside the border. It creates “breathing room” inside the element.
- Border: A line that goes around the padding and content. You can style its thickness, color, and design.
- Margin: The outermost layer. It is a clear area outside the border that separates the element from its neighbors.
The CSS Box Model is illustrated Below
Margin
Border
Padding
Content
Example Code:
.box-model-demo {
width: 300px; /* Content width */
padding: 20px; /* Space inside the border */
border: 5px solid; /* The boundary */
margin: 30px; /* Space outside the element */
background-color: lightblue;
}
Output
Calculating Total Width and Height
By default, the width and height properties only apply to the Content area. If you add padding and borders, the actual space the element takes up on the screen will be larger than the width you set.
The Math:
To calculate the Total Width of an element:
Total Width = Width + Left Padding + Right Padding + Left Border + Right Border
To calculate the Total Height of an element:
Total Height = Height + Top Padding + Bottom Padding + Top Border+ Bottom Border
Note: Margins are not included in the “size” of the box itself, but they do affect the total space the box occupies on the page. So you should also add left and right margins in the total width and top and bottom margin in the total height of the element.
Box-Sizing: Border-Box
Because calculating math every time you add padding is difficult, CSS provides the box-sizing property.
content-box(Default): Width and height only apply to the content. Padding and borders are added on top.border-box(Recommended): Width and height apply to the entire box including padding and borders. The content area shrinks to accommodate them.
Example Code:
/* The Professional Way: Apply to everything */
* {
box-sizing: border-box;
}
.modern-box {
width: 300px; /* This box will ALWAYS be 300px wide, regardless of padding */
padding: 20px;
border: 5px solid black;
}