CSS Box-sizing Property
CSS Box-sizing Property
The box-sizing property in CSS determines how element dimensions are calculated, including its padding and border. It helps control how the total width and height of an element will be calculated when adding internal padding and borders.
Box-sizing Property Values
content-box
- With box-sizing: content-box, the width and height properties include only the content. This means that padding and border are not included in the dimensions and are added separately.
- Element width = content + padding + border.
- This is the standard behavior used by most elements in browsers.
Example:
.element {
box-sizing: content-box;
width: 200px;
padding: 20px;
border: 5px solid black;
}
In this example, the element will have a total width greater than 200px, as padding and border are added to the specified width.
border-box
With box-sizing: border-box, the width and height properties include content, padding, and border. This means that the specified width and height are preserved, and padding and border are built into these dimensions. This mode is convenient as it allows precise control over element dimensions without accounting for additional padding.
Element width = content (includes padding and border).
Example
.element {
box-sizing: border-box;
width: 200px;
padding: 20px;
border: 5px solid black;
}
In this case, the element will have a width of 200px, including padding and border, meaning the size remains exactly as specified.
Important Points
box-sizing: content-box: element dimensions can increase with the addition of padding and border.box-sizing: border-box: dimensions remain constant, including padding and border.
Recommendation:
Use box-sizing: border-box for all elements using the universal selector * to simplify layout and avoid unexpected size changes due to padding and border.