Skip to main content

Box-sizing Property in the CSS Box Model (Live Playground)

The box-sizing property is an essential part of the CSS box model, allowing you to control how the dimensions of an element are calculated. In this tutorial, you will learn about the box-sizing property, how to use it to control element sizing, and the differences between content-box and border-box, along with sample code and simple explanations.

The default box-sizing: content-box

By default, the dimensions of an element are calculated using the content-box model, which means that the width and height properties only apply to the content area, and padding and borders are added on top of those dimensions.

Example:

CSS
div {
background-color: lightblue;
width: 300px;
height: 200px;
padding: 20px;
border: 5px solid darkblue;
}
HTML
<div>This div element uses the default content-box model.</div>

In this example, the div element's total width is 350px (300px content width + 20px left padding + 20px right padding + 5px left border + 5px right border), and the total height is 250px.

Live Playground, Try it Yourself

Changing box-sizing to border-box

When you set the box-sizing property to border-box, the width and height properties include the padding and border, making it easier to control the element's size.

Example:

CSS
div {
background-color: lightblue;
box-sizing: border-box;
width: 300px;
height: 200px;
padding: 20px;
border: 5px solid darkblue;
}
HTML
<div>This div element uses the border-box model.</div>

In this example, the div element's total width is 300px, and the total height is 200px, with the padding and border included in those dimensions.

Live Playground, Try it Yourself

The benefits of using box-sizing: border-box

Using the border-box model can simplify your CSS and make it easier to create consistent and predictable designs.

Example:

CSS
.container {
display: flex;
}

.box {
box-sizing: border-box;
width: 50%;
height: 100px;
background-color: lightblue;
padding: 20px;
border: 5px solid darkblue;
}
HTML
<div class="container">
<div class="box">Box 1</div>
<div class="box">Box 2</div>
</div>

In this example, using the border-box model ensures that the boxes maintain a consistent width, regardless of their padding and border.

Live Playground, Try it Yourself

Conclusion

In this tutorial, you learned about the box-sizing property in the CSS box model, the differences between content-box and border-box, and how to use the box-sizing property to control element sizing. By understanding the role of the box-sizing property in the box model, you can create more visually appealing and consistent designs across your web pages.