dlo.me

Box Sizing that Works on Every Browser

Earlier today, Paul Irish wrote a post on his blog that explains how to deal with an all-too-common issue that all frontend developers face—the div that increases in width and height as soon as you apply padding to it.

An example might be the below.

<style type='text/css'>
div#example {
  background:yellow;
  height:100px;
  width:100px
}
</style>
<div id='example'>Hello, world.</div>

What it looks like:

Hello, world.

Now that doesn’t look too good! Let’s say the goal is to give that yellow box a padding on all sides, let’s say 10 pixels. The impatient web developer does this:

<style type='text/css'>
div#example {
  padding:10px;
  background:yellow;
  height:100px;
  width:100px
}
</style>
<div id='example'>Hello, world.</div>
Hello, world.

Oh no! Our box is bigger! That’s not what we wanted. So we do some quick mental math and subtract the padding from each side from the width and height, and get this.

<style type='text/css'>
div#example {
  padding:10px;
  background:yellow;
  height:80px;
  width:80px
}
</style>
<div id='example'>Hello, world.</div>
Hello, world.

So, this method works, but is messy and hard to maintain. Every time you need to change that padding, you’ll have to change two other attributes as well to keep the content the same size. Paul Irish proposes using the box-sizing: border-box attribute in your CSS, but there are a few cross-browser compatibility issues and jQuery bugs that affect its use. Additionally, if you ever want to use the “normal” box-sizing in your code, you’ll have to start keeping track of which divs have content-box or border-box set in the box-sizing attribute. That is also hard to keep track of.

My recommendation is 100% portable across every browser known to man, and is extremely flexible. Presenting, the box in a box!

<style type='text/css'>
div.padder-10 {
  padding:10px;
}
div#example {
  background:yellow;
  height:100px;
  width:100px
}
</style>
<div id='example'>
  <div class='padder-10'>Hello, world.</div>
</div>
Hello, world.

The outer div will maintain its height and width, and the responsibility for the padding is passed to the inner div.