CSS Box-Sizing
What is Box-Sizing in CSS?
The box-sizing property determines if the element's sizing, including the padding and border, is applied to the content box or to the entire box as the surrounding area.
There are two possible values for box-sizing: .content-box {display: box (default), border-box}.
Content Box Sizing (Default):
Here I specify the box-sizing option by default - which is content-box. The width property is the only way ti specify the content width while the padding and border are added to this width.
div {
width: 200px;
padding: 20px;
border: 2px solid #3498db;
box-sizing: content-box; /* Default box-sizing value */
}
Border Box Sizing:
This example adopts the concept of border-box for box-sizing. The width property which inclusive padding and border is now the sum of its total width displaying as 200 pixels.
div {
width: 200px;
padding: 20px;
border: 2px solid #3498db;
box-sizing: border-box; /* Set box-sizing to border-box */
}
Box Sizing for All Elements:
The following example specifies border-box as the overall sizing on every element (the universal selector '*') of the web page.
* {
box-sizing: border-box; /* Apply border-box sizing to all elements */
}
div {
width: 200px;
padding: 20px;
border: 2px solid #3498db;
}
Responsive Box Sizing:
This example uses border-box sizing for a responsive design. The width and padding are specified as percentages, and the total width of the box remains 50%.
div {
width: 50%;
padding: 5%;
border: 2px solid #3498db;
box-sizing: border-box; /* Set box-sizing to border-box for responsive design */
}
Box Sizing with Flexbox:
This example uses border-box sizing for flex items within a flex container. The padding and border are included in the flex items' total width.
.container {
display: flex;
}
.item {
flex: 1;
padding: 20px;
border: 2px solid #3498db;
box-sizing: border-box; /* Set box-sizing to border-box for flex items */
}
Box Sizing with Grid Layout:
In this case, rectangle highlights bordered-box sizing mechanism for grid items inside a grid container. It does not matter how much content will fit in the grid, it will not overflow from the layout. The width of the cell is calculated for the padding and border included in the grid item.
.container {
display: grid;
grid-template-columns: repeat(2, 1fr);
}
.item {
padding: 20px;
border: 2px solid #3498db;
box-sizing: border-box; /* Set box-sizing to border-box for grid items */
}