CSS `box-sizing` Property
The `box-sizing` property in CSS defines how the total width and height of an element are calculated. By default, an element’s width and height only include the content, but with `box-sizing`, you can change this behavior to include padding and borders.
Common Values for `box-sizing`
- `content-box`: This is the default value. The width and height properties only include the content, and padding and border are added outside of the element’s box.
- `border-box`: The width and height properties include content, padding, and border. This makes it easier to size elements without having to account for padding and borders separately.
Examples of `box-sizing` Values
Example: Default `content-box`
/* Default Box Sizing Example */
.default-box {
width: 200px;
height: 100px;
padding: 20px;
border: 5px solid #000;
box-sizing: content-box; /* This is the default value */
}
Width (200px) + Padding (20px × 2) + Border (5px × 2) = 250px total width.
Example: Using `border-box`
/* Border Box Example */
.border-box {
width: 200px;
height: 100px;
padding: 20px;
border: 5px solid #000;
box-sizing: border-box; /* Includes padding and border in width/height */
}
Width (200px) is the total width, including padding and border. Content area will adjust accordingly.
Advantages of `box-sizing: border-box`
- Ease of Layout: Simplifies the process of sizing elements, making layouts easier to manage.
- Consistent Sizing: Elements can be sized accurately without worrying about additional space from padding and borders.
- Responsive Design: Works better with responsive designs since the total size remains consistent across different screen sizes.
Setting `box-sizing` Globally
You can set `box-sizing` for all elements globally using the universal selector. This is a common practice in modern web development.
/* Set box-sizing globally */
*,
*::before,
*::after {
box-sizing: border-box;
}
This approach ensures that all elements, including pseudo-elements, use `border-box` for sizing, making layout easier to manage.