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.
What it looks like:
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:
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.
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!
The outer div will maintain its height and width, and the responsibility for the padding is passed to the inner div.