The box-sizing property in CSS allows you to control how the width and height of an element are calculated. It can make designing layouts easier by including or excluding padding and border in the element's total width and height.
The box-sizing property can take the following values:
Value | Description | Code | Example |
---|---|---|---|
content-box | This is the default value. The width and height properties (and min/max properties) include only the content, but do not include padding, border, or margin. For example, if you set an element's width to 300px, the content will be 300px wide, and the padding and border will be added outside of this width, making the total width larger. |
|
Content Box Example
|
border-box | The width and height properties (and min/max properties) include the padding and border, but not the margin. This value makes it easier to ensure elements fit within a specific size. For example, if you set an element's width to 300px, the padding and border will be included within this width, making the content area smaller. |
|
Border Box Example
|
Here is how you can apply the box-sizing property to your elements using CSS:
Example: Content-Box
.content-box {
box-sizing: content-box;
width: 200px;
height: 100px;
padding: 20px;
border: 5px solid black;
background-color: lightblue;
}
This example shows an element using the default content-box value, where padding and border are not included in the width and height.
.border-box {
box-sizing: border-box;
width: 200px;
height: 100px;
padding: 20px;
border: 5px solid black;
background-color: lightcoral;
}
This example shows an element using the border-box value, where padding and border are included in the width and height.
*, *::before, *::after {
box-sizing: border-box;
}
It's often recommended to set box-sizing: border-box; globally to ensure consistent sizing across all elements. This can help prevent layout issues that arise from padding and border being added to the width and height of elements.
.div1 {
box-sizing: border-box;
width: 300px;
height: 100px;
padding: 20px;
border: 1px solid blue;
}
.div2 {
box-sizing: content-box;
width: 300px;
height: 100px;
padding: 20px;
border: 1px solid red;
}
This example compares elements with and without box-sizing: border-box; to illustrate the difference in how the box-sizing property affects the element's size.
Here are some important notes and best practices when using the box-sizing property:
*, *::before, *::after {
box-sizing: border-box;
}