Page - Particula Blog Hero
A repository for solving, coding and sharing.

CSS: Changing box-sizing to prevent stretched layouts

The Issue

Something is stretching your nice mobile layout beyond your expected 560px width. The layout displays mostly nice, but you can drag the entire site to the left and see extra space. You keep toggling open elements in the inspector trying to find the culprit lurking in its hideout plotting its next caper. You futz about with overflow: hidden. You get tricky, winnowing down widths until it all fits: "Okay, we've got 20px on each side, so you're now, uh, width: 520px." You start floating and clearing and swearing.

A possible reason is that the standard box model calculates dimensions only for elements themselves, excluding padding and borders. You might have assigned a 560px width to a container, but padding and borders push it wider as a result.

Solution

Change your box-sizing. A number of developers prefer changing the box-sizing from content-box to border-box, which includes padding and borders in width calculations. When I have 560px of space, I usually want its contents to be no more than that.

There are a couple ways to do this. The classic method is to set everything to border-box:

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

This will work nicely in just about all cases, although when you do want something to behave in the standard content-box way, you'll have to override it and all its children. This is the current standard, which is more inheritance-friendly:

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

Other Notes

• Margin is not included, and we typically don’t want it to be. We expect margins to be "outside" an element. I do, anyway. I'm sorry if this, um, marginalizes them.

• The * selector does not include pseudo-elements by default, so if you use the first method, include them.

• This whole border-box behavior used to be "Quirks Mode" for IE6 and earlier. So, IE won that aesthetic round.

 

More Subheader

Client Work. Nothing but the good stuff:

  • Project - Nine Inch Nails - Secondary
  • Project - Harry Potter - Secondary
  • Project - KCET - Secondary
  • Project - NBC - Secondary
  • Project - Jakes - Secondary
  • Project - OWN - Secondary

Pages