CSS3 Box Sizing

By | January 22, 2012

Just a quick one today about the CSS3 property box-sizing. I’ve been busy this week so I’m a little late with my post and also it’s not the one I intended to write but it’s a good tip that I found out this week.
I found out about whilst looking for something else and would have loved to have known about it when helping to create a new homepage at work where we had issues because of the borders on certain elements when resizing the page. It became a real nightmare and I broke the homepage for a couple of hours till we got the properties right.

View Demo

Box sizing allows you to set how, for instance, a div size is calculated (or any DOM element for that matter). As I am sure you all know , an element’s total width (without the margin) is normally calculated from its CSS width value, plus its left and right padding and its border-width.

div {
background: #F00;
width:250px;
padding:10px;
border:10px #fff solid;
height:250px;
}

In the example, the div has a total width of 290px. 250px width plus 20px padding (both sides) plus 20px border (both sides).
We all know this stuff but the problem comes when you start using percentages:

div {
background: #F00;
width:32%;
padding:10px;
border:10px #fff solid;
height:250px;
}

Now there is a problem because you nee to know the width of the parent element before you know what 32% is. Calculations can become very complicated very quickly, making responsive layouts tricky to manage.
At this point, the box-sizing property comes in handy. With this, you can set from which part of the box model the width is calculated. You can set it with padding, with padding and border or just the default.

This property is implemented in all major browsers even IE8+ but with browser-specific prefixes for Firefox and Safari/Chrome.
There is a default which is content-box but you would normally just leave it and let the browser ender it as normal.
A value of border-box means the width is the total width of the content, the padding, and the border. So the first example with the added box-sizing:

div {
background: #F00;
width:250px;
padding:10px;
border:10px #fff solid;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
height:250px;
}

Now the total width is 250px including the padding and border.
Firefox also has an extra value that other browsers don’t: padding-box. Using this value, the width of the element is calculated from its padding and its content and doesn’t include the element’s border. Here’s an example:

div {
background: #F00;
width:250px;
padding:10px;
border:10px #fff solid;
-moz-box-sizing: padding-box;
height:250px;
}

In this code, the 150px width includes the padding, so the width of the content itself would be 270px.
Check out the demo to see the code in action.

View Demo

See ya.

Leave a Reply

Your email address will not be published. Required fields are marked *