由来
IE 的一个 bug 是对于盒子模型的错误解释:在 IE5.x 以及 Quirks 模式的 IE6/7 中,将 border 与 padding 都包含在 width 之内。
同时,由于另外一些浏览器对标准的遵从,我们在精确定义一个在有限空间内显示的 box 时,也需要计算一下:留给它的空间只有那么大,刨去 border 和 padding,我们该把它的 width 写成多少。
这种情况在 CSS3 时代有了改善,得益于这个叫做 box-sizing 的属性,定义 box-sizing: content-box 时,浏览器对盒模型的解释遵从我们之前认识到的 W3C 标准;定义 box-sizing: border-box 时,浏览器对盒模型的解释与 IE6 相同;而定义 box-sizing: padding-box 仅被 Firefox 支持。
概念
属性值:
content-box
(默认值):border和padding不计算入width和height之内
(width和height只包括content)padding-box
:padding计算入width和height之内
(width和height包括content+padding)border-box
:border和padding计算入width和height之内
(width和height包括content+padding+border)兼容性:
值 | Chrome | Firefox | IE | Opera | Safari |
---|---|---|---|---|---|
content-box/border-box | √ | √ | 8.0+ | √ | √ |
padding-box | × | √ | × | × | × |
举例
<!DOCTYPE html>
<html>
<head>
<style>
.div1 {
text-align: center;
width: 200px;
height: 200px;
background-color: pink;
border: 20px solid lightblue;
padding: 20px;
}
.div2 {
text-align: center;
box-sizing: padding-box;
-moz-box-sizing: padding-box;
-webkit-box-sizing: padding-box;
width: 200px;
height: 200px;
background-color: lightblue;
border: 20px solid pink;
padding: 20px;
}
.div3 {
text-align: center;
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
width: 200px;
height: 200px;
background-color: pink;
border: 20px solid lightblue;
padding: 20px;
}
</style>
</head>
<body>
<div class="div1">content-box<br>width:200px;<br>height:200px;<br>border:20px;<br>padding: 20px;</div>
<div class="div2">padding-box<br>width:200px;<br>height:200px;<br>border:20px;<br>padding: 20px;</div>
<div class="div3">border-box<br>width:200px;<br>height:200px;<br>border:20px;<br>padding: 20px;</div>
</body>
</html>
Firefox下的box-sizing:
注意类似的坑:
当使用box-sizing: border-box
时,用line-height使文字上下居中注意要减去border*2
相关链接——
http://www.w3cplus.com/content/css3-box-sizing
https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing
https://css-tricks.com/box-sizing/
http://www.zhangxinxu.com/css3/css3-box-sizing.php