CSS3 box-sizing and making 50% wide padded elements behave

If you are regularly styling forms, you have probably noticed a strange limitation: You simply cannot make a textarea or input 100% wide if it has padding or borders. WAT?

That's because of how the box model is interpreted nowadays (Internet Explorer maybe got it right at some point).

The current default box model only applies the specified size to the content, and then adds padding, border and margin to it. That makes creating 100% wide padded elements virtually impossible.

Does this ring a bell?

eek/gross/stylesheet.css
#column-left, #column-right{
  width: 50%; float: left;
}
.column-inner{
  padding: 10px;
}
some/ugly/layout.html
<div id="column-left">
  <div class="column-inner">
     Hey! I am a padded column on the left of the screen.
  </div>
</div>
<div id="column-right" style="">
  <div class="column-inner">
     Wassup? I'm padded too and floating on the right!
  </div>
</div>

Awful, right? Well, there it comes CSS3 to the rescue!

The shiny new (or not so new!) css3 property box-sizing allows you to change this behavior and use the outer border size as basis when manually specifying the size of an element. Neat!

So you're good to go with just:

why/u/no/using/that/before.css
#column-left, #column-right {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  width: 50%;
  padding: 10px;
  float: left;
}

(You could use a compass mixin for this)

awesome/clean/markup-less/layout.html
<div id="column-left">
  Hey! I am a padded column on the left of the screen.
</div>
<div id="column-right">
  Wassup? I'm padded too and floating on the right!
</div>

This will work in Safari, Chrome, any version of Firefox, and explorer 8+.

There's lots of things you can do using this property and avoid suffering, like:

  • Make 100% width form elements with padding, border & shit
  • Create fluid layouts with any extra tricky markup
  • Add or remove border when hovering any element without making them overflow (and thus, without breaking your layout)

So am I an idiot for not using this before?

Yes, you probably are. But hey! We were too :)