box-sizing is a CSS property that defines how the total width and height of an element are calculated.
π¦ Default Problem in CSS
By default, CSS adds padding and border outside the defined width/height.
div {
width: 200px;
padding: 20px;
border: 5px solid;
}
β‘ Actual width = 200 + 40 + 10 = 250px β
This often breaks layouts.
β
box-sizing Solutions
πΉ 1. content-box (default)
box-sizing: content-box;
- Width/height apply only to content
- Padding + border are added extra
π Total size = content + padding + border
πΉ 2. border-box (recommended)
box-sizing: border-box;
- Width/height include content + padding + border
- Element stays within defined size
π Total size = exactly what you set β
π§ͺ Example
.box {
width: 200px;
padding: 20px;
border: 5px solid;
box-sizing: border-box;
}
β‘ Final width = 200px, not more β
π Best Practice (Used in real projects)
* {
box-sizing: border-box;
}
This makes layouts:
- Predictable
- Easier to manage
- Responsive-friendly
π― Short Interview Answer
box-sizingcontrols how an element’s width and height are calculated.
Withborder-box, padding and borders are included in the defined size, making layouts easier and more predictable.
β One-line summary
box-sizing: border-box prevents layout breaking by including padding and border inside the element’s size.