Why do inputs and selects use different box models?
It appears (at least in IE 8 and Firefox 3) that for <input> elements the width refers to the content, but for <select> elements the width refers to the content + borders. I am explicitly specifying the width in the CSS style.
What's the deal? I would have thought that both are inline replaced elements and would behave identically. Is this behavior consistent with W3C standards? Does it work this way in all major browsers?
Select sizing differs from inputs sizing because of different box-sizing. Input has box-sizing set to "content-box" while select has box-sizing set to 'border-box'. In example below input will be wider than select:
<input type="text" name="a" value="a" style="width:100px; border:5px solid red; padding: 10px;" />
<select name="b" style="width:100px; border:5px solid red; padding: 10px;" /><option value="b">b</option></select>
it is because full width for input will be width+padding(left+right)+border(left+right) and for select full width will be just width (but you know that). To make both element behave same way you have to change box-sizing model. In example below input and select will have exactly the same width*:
<input type="text" name="a" value="a" style="width:100px; border:5px solid red; padding: 10px;" />
<select name="b" style="box-sizing: content-box; width:100px; border:5px solid red; padding: 10px;" /><option value="b">b</option></select>
*use -moz-box-sizing for firefox
As i know this behavior is consistent in all modern browsers (including iE6) but i dont know why it works this way. Don't know any W3 spec where is this particular behavior described. There is note suggesting default styling but it covers only simple attributes - that's why reseting default css is so popular.
I used this on CSS an work perfectly:
input, select
{
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
box-sizing: content-box;
}
With this you force the behavior of inputs and select to be the same.
It is generally a best practice to "reset" the base styles of all controls and other common elements (like html, body, etc.) to a common ground minimum. While not guaranteed to produce perfectly matching controls in all browsers, it gets you much closer. There are a wide variety of premade reset CSS that you can simply use off of the internet. One of the most common is YUI's reset css:
Once resetting your CSS, to resolve the width discrepancy, you would simply need to set a standard default border and padding for your input controls that properly accommodates your sites style.
链接地址: http://www.djcxy.com/p/46898.html上一篇: 可定制的工具栏在WPF中
下一篇: 为什么输入和选择使用不同的盒子模型?