Dave Woods - Freelance Web Design Warwickshire

CSS3 Box sizing

The box model is pretty straight forward in most scenarios so we know that when creating CSS for an element that width + border + margin + padding = the rendered width. However, when dealing with percentage widths things become a bit trickier but there is a solution.

The block solution

The easiest thing to do is to use display: block; and most elements will play ball:

#element { display: block; margin: 10px; padding: 10px; border: 1px solid #ccc; }

By using display: block; this element will fill the total width available after taking into consideration the margin, padding and borders.

However, that doesn’t solve all problems.

100% width textarea with padding and borders

The biggest problem I’ve come across is when dealing with the textarea element. We may want to style it so that it has a 1px border and has a set amount of padding. However, by setting display: block; on a textarea, this solution doesn’t work.

The solution to this is to use CSS3 box-sizing:

textarea { width: 100%; box-sizing: border-box; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; -ms-box-sizing: border-box; padding: 10px; border: 1px solid #ccc; }

By setting the box-sizing as border-box, this tells the browser to use the width declared as the total value and to place any padding and borders inside the box.

Summary

This isn’t such a problem when dealing with fixed layouts but when dealing with fluid layouts where you aren’t sure what width a column is, this can be a huge headache.

When I first found this solution it was like a eureka moment. Unfortunately this doesn’t work in IE7 but you should be able to create a solution which degrades gracefully with some fixed widths and min-widths whilst using box-sizing for all other browsers including IE8 and upwards.