Which variant is more suitable to specify box-sizing for the whole document?

297 Views Asked by At

Sometimes I see this kind of code in the very beginning of the document:

html {
    box-sizing: border-box;
}

*, *:before, *:after {
    box-sizing: inherit;
}

I don't understand the purpose of :before and :after pseudo-elements in it. Why isn't the

*{
    box-sizing: border-box;
}

just enough?

Thanks :)

1

There are 1 best solutions below

2
On

You can read a very good explanations here. It explains perfectly your doubt.

The "Old" border-box Reset
The earliest box-sizing: border-box; reset looked like this:

* { box-sizing: border-box; }

This works fairly well, but it leaves out pseudo elements, which can lead to some unexpected results. A revised reset that covers pseudo elements quickly emerged:

Universal Box Sizing

*, *:before, *:after { box-sizing: border-box; }

This method selected pseudo elements as well, improving the normalizing effect of border-box. But, the * selector makes it difficult for developers to use content-box or padding-box elsewhere in the CSS. Which brings us to the current frontrunner for best practice:

Universal Box Sizing with Inheritance

html { box-sizing: border-box; } *, *:before, *:after { box-sizing: inherit; }

This reset gives you more flexibility than its predecessors — you can use content-box or padding-box (where supported) at will, without worrying about a universal selector overriding your CSS. We went into more depth on this technique and the reasoning behind it in "Inheriting box-sizing Probably Slightly Better Best Practice". One potential gripe with it is that box-sizing isn't normally inherited, so it's specialized behavior, not quite the same as something you'd normally put in a reset.




Other sources: