Problem
I’ve set all of my inputs, textareas and select boxes to 230px and yet…So lets say you wanna hook up a form with consistent input sizes and you’d like for them all to match. You would likely write something similar to the following css to achieve the goal. One would think that by assigning identical width values to both inputs and selects that they would be the same size when rendered in the browser. However this proves to not always be the case.
#MyForm input,
#MyForm select,
#MyForm textarea{
width:230px;
/* my awesome style */
}
Resolution
So, how do we fix it? Well there are a number of options that I don’t like, and one that I do. If you wanna know what the other options are look-em up. However I warn you they suck and may leave you sucking too, so without further ado.
input, select, textarea{
width:230px;
-moz-box-sizing:border-box; /* FireFox */
-webkit-box-sizing:border-box; /* Safari & Chrome */
-ms-box-sizing:border-box;/* IE 8 */
box-sizing:border-box; /* opera, IE 9 and other css3 standard compliant browsers */
}
Why?
The Box ModelI’m not the kind’a guy that can simply copy and paste code. I need to know why it was necessary in the first place. So if you’re like me and enjoy honing your ninja skills, lets find out why these selects are so un-ninjaly. The truth is select boxes are made of leftover lasagna and week old cheese… Well ok, it’s not quite that gross, but almost. When browsers render elements they uses the box model to determine how to display the element in relation to other elements. So apparently the select (and the textarea) use a different methods for interpreting the box model than inputs making them appear shorter. This is where our friendly new CSS3 propery box-sizing saves the day as it allows us to force the (compliant) browser to use what portion of the box-model we want it to use.
Final Remarks
The Boss Ninja and The Box ModelNow there is a ton more going on here than I’ve gone into for the sake of this little post. If you want to know more about the box-model and what exactly is going on behind the scenes when you muck around with the box-sizing property check out the articles in the links below. I did make a little box-sizing comparison graphic that almost does the madness justice, you’ll find it to the right. I hope this was helpful and I look forward to your comments.
Links
- Box sizing and the box model http://css-tricks.com/7323-box-sizing/