不同浏览器上input与select宽度显示不同的本质原因

https://blog.csdn.net/github_22022001/article/details/47279793

做表单开发时经常碰到一个问题,input和select是其中最常用的两个标签,但是有个问题很棘手。input和select是两种不同的和模型,如果只是简单的将两者的width设置成一样,将会出现下面的效果:

  1.  
    <!DOCTYPE html>
  2.  
    <html>
  3.  
    <head>
  4.  
    <meta charset="utf-8">
  5.  
    <style type="text/css">
  6.  
    *{margin:0;padding:0;}
  7.  
    body{margin: 50px;}
  8.  
    input{outline-style: none;}
  9.  
    .input{
  10.  
    100px;
  11.  
    }
  12.  
    .select{
  13.  
    100px;
  14.  
    }
  15.  
    </style>
  16.  
    </head>
  17.  
    <body>
  18.  
    <div><input class="input" type="text" /></div>
  19.  
    <div>
  20.  
    <select class="select">
  21.  
    <option>opt1</option>
  22.  
    <option>opt2</option>
  23.  
    <option>opt3</option>
  24.  
    </select>
  25.  
    </div>
  26.  
    </body>
  27.  
    </html>

不同浏览器上input与select宽度显示不同的本质原因

并且是在所有的浏览器中都是这样,下面直接来看看各个浏览器中的盒模型布局就会一目了然;

chrome:

不同浏览器上input与select宽度显示不同的本质原因

firefox:

不同浏览器上input与select宽度显示不同的本质原因

IE:(这里IE要分代,IE8之前是一代,IE9之后是一代,看图明了)

不同浏览器上input与select宽度显示不同的本质原因

这两个标签在不同浏览器上的表现明显不同,总结一下:

模型:border + realwidth

chrome -> firefox -> IE9+ ->IE8-

select:

2*2 + 98 -> 0*2 + 100 -> 1*2 + 98 -> 1*2 + 100   (102 100 100 102)

input:

2*2 + 100 -> 1*2 + 100 -> 1*2 + 100 -> 1*2 + 100   (104 102 102 102)

无论是哪一种情况,都会多出来2px(IE8-看似都是102,但是效果还是多出来2px),这个足够让处女座抓狂!我不是处女座,但是在实践过程中也为此抓狂过,不探索出本质原因和解决方案实在让人不安,还好是有解!其实加个内边距,一切疑惑都会迎刃而解。

select的css width样式,包含边框和内边距,即:realwidth=CSS width。

而input的css width样式,则不包含边框和内间距,realwidth=CSS width + border + padding。

解决的方法如下:(下图只是chrome的布局,大家可以试试在各个浏览器中都是有规可循的)

  1.  
    <!DOCTYPE html>
  2.  
    <html>
  3.  
    <head>
  4.  
    <meta charset="utf-8">
  5.  
    <style type="text/css">
  6.  
    *{margin:0;padding:0;}
  7.  
    body{margin: 50px;}
  8.  
    div{margin-bottom:1px;}
  9.  
    input{outline-style: none;}
  10.  
    select div{border: 0;}
  11.  
    .input{
  12.  
    96px;
  13.  
    border: 1px solid #707070;
  14.  
    padding: 1px!important;
  15.  
    } /* 96+1*2+1*2=100 */
  16.  
    .select{
  17.  
    100px;
  18.  
    padding:1px;
  19.  
    border: 1px solid #707070;
  20.  
    } /* 98+1*2+0*2=100 */
  21.  
    </style>
  22.  
    </head>
  23.  
    <body>
  24.  
    <div><input class="input" type="text" /></div>
  25.  
    <div>
  26.  
    <select class="select">
  27.  
    <option>opt1</option>
  28.  
    <option>opt2</option>
  29.  
    <option>opt3</option>
  30.  
    </select>
  31.  
    </div>
  32.  
    </body>
  33.  
    </html>

不同浏览器上input与select宽度显示不同的本质原因 
总结: 

设置select的CSS width=input 的CSS width border padding

Done perfectly!