CSS box-sizing property
The box-sizing
Property in CSS
The box-sizing
property in CSS is used to control how the total width and height of an element are calculated. It determines whether padding and borders are included in the element's total width and height or not. This property helps in managing the layout and design of elements, especially when dealing with complex layouts or responsive designs.
Values of box-sizing
content-box
- Default Value: This is the default value for the
box-sizing
property. - Calculation: The width and height you set for an element only apply to the content box. Padding and border are added outside of this width and height.
- Example Calculation:
- If you set
width: 200px
,padding: 20px
, andborder: 5px solid
, the total width will be200px (content) + 20px (left padding) + 20px (right padding) + 5px (left border) + 5px (right border) = 250px
.
- If you set
.content-box { box-sizing: content-box; width: 200px; padding: 20px; border: 5px solid black; }
- Default Value: This is the default value for the
border-box
- Calculation: The width and height you set for an element include the content, padding, and border. This makes it easier to manage the size of elements because the total size remains as specified.
- Example Calculation:
- If you set
width: 200px
,padding: 20px
, andborder: 5px solid
, the total width will be exactly200px
, including the content, padding, and border.
- If you set
.border-box { box-sizing: border-box; width: 200px; padding: 20px; border: 5px solid black; }
Examples
Using
content-box
<div class="content-box">Content Box</div>
.content-box { box-sizing: content-box; width: 200px; padding: 20px; border: 5px solid black; background-color: lightblue; }
- In this case, the total width will be
200px (content) + 20px (padding) + 5px (border) = 250px
.
- In this case, the total width will be
Using
border-box
<div class="border-box">Border Box</div>
.border-box { box-sizing: border-box; width: 200px; padding: 20px; border: 5px solid black; background-color: lightcoral; }
- Here, the total width will remain
200px
, including content, padding, and border.
- Here, the total width will remain
Use Cases
- Layout Management:
border-box
simplifies layout calculations, especially for responsive designs, as it ensures the element’s total size is consistent. - Consistent Sizing: Use
border-box
when you want the padding and border to be included in the element’s specified dimensions, making it easier to maintain consistent sizing. - Form Elements: Applying
border-box
to form elements helps in ensuring their sizes remain predictable, especially when adding padding or borders.