The Box Sizing Reset in CSS
Sizing elements is crucial in front-end Web development. Talking about CSS, every now and then you need to size things up if you are into architecting web layouts and components.
Beginning up with CSS? Read this elemenatary guide on CSS Box-model.
You might have been dealing with a lot of mathematical calculations to size up different elements, if you are not using this CSS box-sizing reset.
You might already know about box-sizing
CSS property, that lets you choose a sizing nature for the box. By default, it is set to content-box
. The border-width
and padding
values when added to a content-box, are exclusively added to the whole width of the box.
Another possible type of box-sizing is border-box
, which lets our box element to include the border-width and padding values.
Now, let me give you an example here. Say you have a simple <div>
with a padding of 1em, and a solid black border of 1px. Note that the box-sizing is not set for the div at the moment, i.e. it is a content-box by default.
<div>Our simple div</div>
div {
padding: 1em;
border: 1px solid;
}
This div will bleed out of the viewport. Why? Because, the border-width and padding values are added exclusively to the width of the div, and hence the net width of the div (say N) becomes:
/**
* total width of `div` = 100%
* total border-width = 1px * 2
* total padding = 1em * 2
*/
N = 100% + (1em * 2) + (1px * 2)
The values above are multiplied by 2 because they are applied on the both left and right sides. In order to fit an element completely inside the viewport and avoid it from bleeding out, you’ll always need to do some math for an element which is really boring as well as tiring.
Is there any way to get the padding and border-width added inclusively to the box width? Yes!
Now, if you set the box-sizing
for our div to border-box
, it will magically fit inside the viewport without any math calculations involved!
div {
box-sizing: border-box;
padding: 1em;
border: 1px solid;
}
But then, you’ve to set box-sizing
for every element you need to size-up perfectly. And here comes the need of our Box-sizing Reset.
CSS box-sizing Reset
The box-sizing Reset takes care of the box-sizing of every element by setting it to border-box
using the universal CSS selector.
It would be little better practice if we set the box-sizing
to border-box
for the html
element and then get it inherited for all the elements and pseudo-elements by making use of universal CSS selector (*).
Here is the final code snippet for the CSS box-sizing reset:
html {
box-sizing: border-box;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
Best thing about this reset is, that it saves you time and you don’t have to write the same thing again-and-again with it.
I guess most of you have already been implementing this reset now. Let me know more about how you are using it, and what changes have you made it to suit your needs. Cheers!
Load Comments...