What is box-sizing in CSS: Explanation and Usage
box-sizing in CSS controls how the total width and height of an element are calculated. It decides whether padding and border are included inside the element's set width and height (border-box) or added outside (content-box).How It Works
Imagine you have a box with a fixed width. Normally, when you add padding or borders, the box gets bigger because these are added outside the content area. This is like wrapping a gift: the box is the gift, and the wrapping paper (padding and border) adds extra size.
The box-sizing property changes this behavior. When set to border-box, the padding and border are included inside the fixed width, so the box size stays the same. It's like having a gift box where the wrapping paper fits perfectly inside the box edges.
This helps keep layouts neat and predictable, especially when designing responsive pages or complex interfaces.
Example
This example shows two boxes with the same width and padding but different box-sizing values. Notice how the total size changes.
div {
width: 150px;
padding: 20px;
border: 5px solid black;
margin-bottom: 10px;
background-color: lightblue;
}
.box1 {
box-sizing: content-box;
}
.box2 {
box-sizing: border-box;
}When to Use
Use box-sizing: border-box when you want to control the total size of elements precisely, including padding and borders. This is very helpful in responsive design, where elements need to fit neatly inside containers without unexpected overflow.
Many developers apply box-sizing: border-box globally to all elements to simplify layout calculations and avoid surprises when adding padding or borders.
Key Points
- content-box (default): width and height apply to content only; padding and border add outside.
- border-box: width and height include content, padding, and border.
- Using
border-boxmakes layout sizing easier and more predictable. - Common practice is to set
box-sizing: border-boxon all elements.