box-sizing
Definition
box-sizing
is a CSS property that allows you to control the size and dimensions of an element, including the padding and borders. It is used to change the default box model of an element, which is the way that the size and dimensions of an element are calculated by the browser.
Examples
This will make all elements on the page have the border-box box model, which includes the padding and border in the overall size of the element:
* {
box-sizing: border-box;
}
This will make the width and height of elements with the class "my-class" include the padding and border, adjusting the content size accordingly:
.my-class {
width: 300px;
height: 200px;
padding: 10px;
border: 2px solid #000;
box-sizing: border-box;
}
This will set the box-sizing property of elements with the class "my-class" to content-box when the screen width is at least 768px:
@media screen and (min-width: 768px) {
.my-class {
box-sizing: content-box;
}
}
Values
Value | Description |
---|---|
content-box | This is the default behavior, the width and height of an element are determined by the content inside it, and any padding or border is added to the overall size of the element. |
border-box | In this model, the width and height of an element include the padding and border, and the content is adjusted accordingly. This means that if you set a width and height on an element with border-box, the element will always be that size, even if you add padding or borders. |
Best Practices
- Use a global reset: To ensure that your layout is consistent across different browsers and devices, it's a good practice to use box-sizing: border-box as a global reset. This will make all elements on the page have the border-box box model, which includes the padding and border in the overall size of the element.
- Be consistent: Once you've chosen a box model, make sure to use it consistently throughout your layout. Mixing content-box and border-box can make your layout unpredictable and hard to maintain.
- Use it with media queries: box-sizing property can be used in combination with media queries to change the layout of your elements depending on the screen size. This can be useful for responsive design, allowing you to adjust the size and dimensions of your elements for different devices.
- Test on different browsers: Make sure to test your layout on different browsers and devices to ensure that it looks and functions correctly. Some older browsers may not support the box-sizing property or may have limited support for it.
- Avoid using it on small elements: It's not necessary to use box-sizing on small elements that have no padding or border. It can make your code more complex and harder to maintain.
Browser Compatibility
Chrome | Firefox | Safari | Internet Explorer | Microsoft Edge | Opera |
---|---|---|---|---|---|
Yes | Yes | Yes | Yes | Yes | Yes |