How to Use border-box in CSS for Better Layout Control
Use
box-sizing: border-box; in CSS to make an element's width and height include its padding and border. This helps keep layouts consistent and easier to manage because the total size won't grow when you add padding or borders.Syntax
The box-sizing property controls how the total width and height of an element are calculated.
content-box(default): Width and height include only the content, padding and border add extra size.border-box: Width and height include content, padding, and border all together.
css
selector {
box-sizing: border-box;
}Example
This example shows two boxes with the same width and padding. The first uses the default content-box, so its total size is bigger. The second uses border-box so the total size stays the same.
css
html, body {
margin: 0;
padding: 0;
font-family: Arial, sans-serif;
}
.box {
width: 200px;
padding: 20px;
border: 5px solid #333;
margin: 10px;
background-color: #f0f0f0;
}
.content-box {
box-sizing: content-box;
}
.border-box {
box-sizing: border-box;
}Output
<div style="width: 200px; padding: 20px; border: 5px solid #333; background-color: #f0f0f0; margin: 10px; box-sizing: content-box;">Content-box (total width 250px)</div><div style="width: 200px; padding: 20px; border: 5px solid #333; background-color: #f0f0f0; margin: 10px; box-sizing: border-box;">Border-box (total width 200px)</div>
Common Pitfalls
Many beginners forget that padding and border add to the element's size by default, causing layout issues. Without border-box, adding padding or border can break your design by making elements bigger than expected.
Also, applying box-sizing: border-box; only to some elements can cause inconsistent layouts. It's common to apply it globally to all elements.
css
/* Wrong: padding increases size unexpectedly */ .box { width: 200px; padding: 20px; border: 5px solid black; /* box-sizing not set, defaults to content-box */ } /* Right: total size stays 200px */ .box { width: 200px; padding: 20px; border: 5px solid black; box-sizing: border-box; }
Quick Reference
- box-sizing: content-box; - Default, width/height exclude padding and border.
- box-sizing: border-box; - Includes padding and border in width/height.
- Use
border-boxfor easier and predictable layouts. - Apply globally with
* { box-sizing: border-box; }for consistency.
Key Takeaways
Use
box-sizing: border-box; to include padding and border in element size.This makes layout sizing easier and prevents elements from growing unexpectedly.
Apply
border-box globally for consistent sizing across all elements.Without
border-box, padding and border add extra size beyond width and height.Remember to test your layout in the browser to see the effect visually.