martin-brennan

articles / archive / about

Box-Sizing Border-Box for CSS Grids

I was working on a grid system in CSS for a style framework I’m making for work, and I ran into a few problems when styling the grid. Specifically, I was having trouble with aligning all of the columns side-by-side while simultaneously giving each column sufficient padding. There is a CSS property called box-sizing, which has a default value of content-box. The problem with this is that for block elements such as divs, properties like borders and padding add width to the element, even if it already has a fixed width. This is particularly troublesome with grids, because we need to have each column the correct width regardless of padding applied to it.

Thankfully, there is another value that can be used for the box-sizing property called border-box, which ensures the element that it is applied to stays the same width, regardless of any padding or borders applied to it. Chris Coyier has a great article on how this box model applies to grids:

Don’t Overthink it Grids by Chris Coyier

And Paul Irish also has an in-depth explanation about the box model and the usage border-box. The article is a great read and lists the pros of using this property:

* { Box-sizing: Border-box } FTW

  • Brett Andrews

    I think that if browsers didn’t have to worry about being largely backwards compatible, this would by now be the default. Are you making your own grid system?

    • http://www.martin-brennan.com/ Martin Brennan

      Yeah I think so too, it makes a lot more sense than content-box. Yeah I made my own one for a CSS framework for work, because I’ve done a complete rewrite of our CSS. It’s like our own internal twitter bootstrap!