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

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

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <style type="text/css">
    *{margin:0;padding:0;}
    body{margin: 50px;}
    input{outline-style: none;}
    .input{
      width:100px; 
    } 
    .select{
      width:100px;
    } 
  </style>
</head>
<body>
    <div><input class="input" type="text" /></div>
    <div>
        <select class="select">
          <option>opt1</option>
          <option>opt2</option>
          <option>opt3</option>
        </select>
    </div>
</body>
</html>


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

chrome:


firefox:

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


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

模型: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的布局,大家可以试试在各个浏览器中都是有规可循的)

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <style type="text/css">
    *{margin:0;padding:0;}
    body{margin: 50px;}
    div{margin-bottom:1px;}
    input{outline-style: none;}
    select div{border: 0;}
    .input{
      width:96px; 
      border: 1px solid #707070;
      padding: 1px!important; 
    } /* 96+1*2+1*2=100 */
    .select{
      width:100px;
      padding:1px;
      border: 1px solid #707070;
    } /* 98+1*2+0*2=100 */
  </style>
</head>
<body>
    <div><input class="input" type="text" /></div>
    <div>
        <select class="select">
          <option>opt1</option>
          <option>opt2</option>
          <option>opt3</option>
        </select>
    </div>
</body>
</html>

总结:

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

Done perfectly!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值