The CSS Box Model
In CSS, every single element rendered on a page is treated as a rectangular box. The CSS Box Model defines how the dimensions and spacing of these boxes are calculated. Mastering the box model is the most important milestone for building reliable web page layouts.
The Four Layers of the Box Model
From the inside out, every element consists of four distinct layers:
- Content: The actual text, image, or child elements located in the center. Its size is controlled by
widthandheight. - Padding: The transparent spacing immediately surrounding the content, inside any visible border. It provides breathing room between text and borders.
- Border: A decorative boundary surrounding the padding and content. You can customize its width, style, and color.
- Margin: The clear space outside the border that separates this element from adjacent elements on the page.
.card {
width: 320px;
padding: 24px;
border: 2px solid #e2e8f0;
margin: 16px auto;
box-sizing: border-box;
}
The Power of box-sizing: border-box
By default, browsers calculate an element's total visible width using content-box. In this legacy mode:
Total Width = width + padding-left + padding-right + border-left + border-right.
This often leads to layout breakages because adding padding expands the element beyond its designated width. To prevent this headache, modern web developers set box-sizing: border-box. With border-box, any padding and border are absorbed inside the specified width, ensuring predictable dimensions.
*, *::before, *::after {
box-sizing: border-box;
}
Key takeaways
- Every element on the web is composed of content, padding, border, and margin.
- Padding creates internal breathing room; margin creates external separation.
- Margins can collapse vertically between adjacent block elements.
- Apply
box-sizing: border-boxglobally to make sizing intuitive and predictable.