CSS Sanity Tip for Programmers

I’m a programmer. I’ll admit it. I’m a professional nerd who, for some reason, thinks the web is awesome. I’ll be honest. I hate how difficult layout is in HTML sometimes. Seriously. How many times have YOU tried to get your margins to play nice with floated, bordered elements, and had to change the border width by 3 pixels in a floated column layout? You probably just about shot yourself. Why? Because the default box model when laying things out since forever and a half ago (e.g. 3 internet years) is box-sizing: content-box;.

What does it mean? content-box means that the box layout is measured from the outer edge of the content. So if I set width: 50px the box that represents that html element is going to be 50px wide. What sucks, and is really weird about this at times, is when we add a margin to our box like this margin: 5px. All of a sudden the ‘actual size’ of the box now increased by 10px! (5px on each side). In addition, margins aren’t “distance away from the edge of another box” like you’d expect, it’s “distance away from the edge of another content box”. That’s why when you have paragraphs next to each other and one has 5px margin and the next one has 10px margin, the paragraphs are 10px apart, not 15px like you might expect.

How do I fix it?

  1. * {
  2. -moz-box-sizing: border-box;
  3. -webkit-box-sizing: border-box;
  4. box-sizing: border-box;
  5. }

Uh. Ok. What does that do? THAT will change every element to measure everything from the outside of your box. So now, when you have two paragraphs, and you give one 5px margin and the other 10px margin, they are going to be 15px apart. If your a developer / programmer who works with programmatic layouts on a day to day basis and gets frustrated by HTML and CSS, try this out. It’ll probably save you LOADS of headaches.

While your at it, read read this post by Paul Irish, because Paul Irish is awesome, and because it covers this in more depth.