loading...

Discussion on: 5 CSS tips you didn't know you needed

Collapse
quantumsheep profile image
Nathanael Demacon

The most useful trick I use in every project is:

* {
  box-sizing: border-box;
}

Which prevent breaking box dimensions with margin, padding or borders.

Collapse
sduduzog profile image
Beautus S Gumede

This should be default

Collapse
javamajk profile image
JavaMajk

Yup, ..to be extra safe :D


  html {
    box-sizing: border-box;
  }
  *, *:before, *:after {
    box-sizing: inherit;
  }
Collapse
giacomosorbi profile image
Giacomo Sorbi

Mh, the * selector is relatively very expensive: I would use it rather sparingly.

Thread Thread
equinusocio profile image
Mattia Astorino

No. The * is the less expensive. Check some talk about performances by csswizardry

Thread Thread
giacomosorbi profile image
Giacomo Sorbi

Googling quickly, they still seem to confirm it among the less efficient: csswizardry.com/2011/09/writing-ef...

Thread Thread
equinusocio profile image
Mattia Astorino

8 years old post...

Thread Thread
giacomosorbi profile image
Giacomo Sorbi

This one is much more resent and confirms that * is still more expensive: sitepoint.com/optimizing-css-id-se...

Collapse
quantumsheep profile image
Nathanael Demacon

It seems like the same thing? :(

Thread Thread
equinusocio profile image
Mattia Astorino

No. The second snippet allows you to define a global box-sizing but let elements to inherit or change the behaviour

Thread Thread
quantumsheep profile image
Nathanael Demacon

Oh ok! So your way is better for sure!

Thread Thread
rinatvaliullov profile image
4rontender

It's old trick, man

box-sizing

Collapse
jonny_goodwin profile image
Jonny Goodwin πŸš€

I think that using box-sizing: inherit;’ can be bad. If you do this, and decide to change box-sizing on an element, all of that elements children will also have their box-sizing changed.

Unless you are sure you want that to happen, it’s probably best just to use β€˜box-sizing: border-box;’ to ensure that all elements use β€˜border-box’. If any elements need a different box-sizing, you would override it with more specificity.

Thread Thread
javamajk profile image
JavaMajk

Yeah indeed, things can get messy in this case.

Thread Thread
dan503 profile image
Daniel Tonon

I was a box-sizing: inherit; person, then I realised this is super useful:

.page-restrictor {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  box-sizing: content-box;
}

It means that when the screen is less than 1240px wide, it will have a 20px gap down either side of the screen with no need for media queries.

This technique doesn't work with box-sizing: inherit; though.