CSS3系列教程——Box-sizing
九月 24, 2010
9 comments
本文翻译自CSS3.info,并稍加改动,原文地址:Box-sizing, box-model fixes for the simple people。
永远不能完全理解box模型大小的计算?CSS3提供了一个新属性,即:box-sizing,它可以让你有计算的改变浏览器中元素的宽度。
box-sizing一共有content-box和border-box两个属性,其中content-box是默认属性:
content-box: element width=content+border+padding(此值维持css2.1盒模型的组成模式)
border-box:element width=content(此值改变css2.1盒模型组成模式)
Firefox支持这个属性需要加上前缀 –moz-,即 –moz-box-sizing;Webkit内核浏览器使用的是 -webkit-box-sizing;IE8以上浏览器使用的是 –ms-box-sizing;Opera直接用 box-sizing就可以了。
下面是一个取自W3C的例子,并稍加改动:W3C中关于box-sizing的例子。
这个DIV应该站在左半边
这个DIV应该站在右半边
上面两个DIV应该会水平并排显示,每一个DIV(包括边框)将占总容器的50%。如果正好相反,一个DIV堆叠在另一个DIV的上面,就说明你的浏览器不支持box-sizing。
CSS代码:
div.container {
width:30em;
border:1em solid black;
}
div.split {
-ms-box-sizing:border-box; //IE8+
-moz-box-sizing:border-box; //Firefox
-webkit-box-sizing:border-box; //Webkit内核(Chrome、Safari)
box-sizing:border-box; //标准样式 Opera
width:50%;
border:1em silver ridge;
float:left;
}
HTML代码:
<div class="container"> <div class="split">这个DIV应该站在左边。</div> <div class="split">这个DIV应该站在右边。</div> 上面两个DIV应该会水平并排显示,每一个DIV(包括边框)将占总容器的50%。如果正好相反,一个DIV堆叠在另一个DIV的上面,就说明你的浏览器不支持box-sizing。 </div>
哦 难怪呢 和我的浏览器有关系!
[回复]
jayuh
回复:
九月 26th, 2010 at 14:44
CSS3,大部分Firefox都支持,只有少部分不支持。像上文box-sizing这个属性就是支持的。
[回复]
I like that news super useful. Thanks for this post
[回复]
jayuh
回复:
十月 23rd, 2010 at 21:17
No thanks.
[回复]
哥,你笔误了
content-box: element width=content+border+padding(此值维持css2.1盒模型的组成模式)
border-box:element width=content(此值改变css2.1盒模型组成模式)
这写反了啊~
content-box:element width=content
border-box: element width=content+border+padding
这个属性相当给力,非常实用啊!
[回复]
Jayuh
回复:
六月 1st, 2011 at 11:08
我没写反,你再好好想想。
[回复]
content-box: element width=content+border+padding(此值维持css2.1盒模型的组成模式)
border-box:element width=content(此值改变css2.1盒模型组成模式)
这么翻译误导多少人啊
[回复]
By default, box-sizing is set to content-box. With that set, it calculates width and height as specified by CSS 2.1, adding the border-width and border-height and the padding to the size of the box. By setting it to border-box, you can force the browser to instead render the box with the specified width and height, and add the border and padding inside the box.
[回复]
你是写反了
[回复]