samedi 5 mai 2012

CSS box model hacking

Want to make an HTML element fill 100% of its parent’s width but also give it a border and/or some padding? Since the width of an element is exclusive of its border and padding this can be a pain. However there’s a fairly simple CSS solution that works cross-browser.

Here’s an example. Both input boxes are set to width: 100% and have padding: 5px. The first input shows the problem. Because the padding and border are added to the width of the element it overflows its container. The box model of the second input has been modified so that the padding and border are inside the declared width.

The trick to modifying the box model is to set box-sizing: border-box. Unfortunately that’s not a cross-browser property, only Opera supports it at the moment. To get the same effect in other browsers you will also need to set browser-specific versions as well:

   -moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
-ms-box-sizing: border-box;
box-sizing: border-box;
Note that Internet Explorer only supports the -ms-box-sizing property from version 8 upwards so you should probably be judicious with this technique or use an alternative method to get a similar effect in IE7 and below.

Aucun commentaire:

Enregistrer un commentaire