Home >Web Front-end >CSS Tutorial >what does box-sizing: border-box actually do?
When I first started learning CSS, I saw box-sizing: border-box in almost every CSS file I encountered. Like many beginners, I copied it without understanding its purpose. If this sounds familiar, don't worry—you’re not alone.
What is box-sizing?
The box-sizing property in CSS controls how the width and height of an element are calculated. There are three main values:
Why box-sizing: border-box?
Here’s why box-sizing: border-box is so helpful:
Here’s a simple example to illustrate the difference between "content-box"and "border-box":
Content box
<div class="content-box"> <p>content-box</p> </div>
.content-box { background-color: red; width: 200px; padding: 20px; border: 10px solid black; text-align: center; color: white; }
As shown in the screenshot, the box with box-sizing: content-box has a total width of 260px. Here's why:
200px is the width set for the content area, 20px on each side adds up to 40px in total (20px + 20px), 10px on each side adds up to 20px in total (10px + 10px).
Total Width: 200px (content) + 40px (padding) + 20px (border) = 260px
Why? With content-box, the width you set is only for the content inside the box. Padding and border are added to this width, increasing the total size of the box.
Border box
<div class=" border-box"> <p>border-box</p> </div>
.border-box { box-sizing: border-box; background-color: green; width: 200px; padding: 20px; border: 10px solid black; text-align: center; color: white; }
In contrast, the box with box-sizing: border-box has a total width of 200px. Here’s why:
200px is the width set for the entire box, including content, padding, and border, 20px on each side (included within the 200px width), 10px on each side (included within the 200px width).
Total Width: The width of 200px encompasses the content, padding, and border altogether. No additional space is added outside this width.
Why? With border-box, the width you set covers everything within the box, so the total size remains as specified, without extra padding or border extending beyond the given width.
Understanding and using box-sizing: border-box can simplify your CSS and make your layouts more predictable and easier to manage. If you had no idea about it I hope this explanation clears things up.
You can view and experiment with the code used in this example on CodePen.
If you enjoyed this post, connect with me on LinkedIn, and Twitter!
The above is the detailed content of what does box-sizing: border-box actually do?. For more information, please follow other related articles on the PHP Chinese website!