Understand the CSS box model — content, padding, border, and margin — and learn how box-sizing controls how element dimensions are calculated.
In CSS, every HTML element is treated as a rectangular box. The box model describes the space an element occupies and consists of four layers, from inside to outside:
width and height.Understanding the box model is essential because it directly affects layout. The total space an element takes up is the sum of its content, padding, border, and margin.
<style>
.box {
width: 200px;
height: 100px;
padding: 20px;
border: 3px solid darkblue;
margin: 16px;
background-color: lightyellow;
}
</style>
<div class="box">This box has padding, border, and margin.</div>
<!--
Total width = 200 + 20*2 + 3*2 + 16*2 = 278px
(content + padding + border + margin)
-->By default, width and height only apply to the content area. Padding and border are added on top, making the element larger than the specified width. This is called content-box sizing and it often leads to unexpected layout issues.
The border-box model changes this behavior so that width and height include padding and border. The content area shrinks to accommodate them:
.box {
box-sizing: border-box;
width: 200px;
padding: 20px;
border: 3px solid black;
}
/* Total width is exactly 200px */
/* Content area = 200 - 40 - 6 = 154px */Most modern CSS resets apply border-box to all elements:
*, *::before, *::after {
box-sizing: border-box;
}This makes sizing much more predictable and is considered a best practice.
An element has width: 200px, padding: 10px on all sides, and border: 5px solid. With the default box-sizing (content-box), what is the total rendered width?