原始网址:http://www.w3schools.com/css/css3_box-sizing.asp
翻译:
CSS3 Box Sizing
CSS3 Box Sizing
CSS3 box-sizing 属性允许我们将内边距和边框包含在元素的总宽高之内。
Browser Support
表格里的数字代表对 CSS3 属性全面支持的各浏览器的第一个版本号。
数字之后跟从 -webkit-
或 -moz-
指定带前缀工作的第一个版本号。
属性(Property) | ![]() | ![]() | ![]() | ![]() | ![]() |
---|---|---|---|---|---|
box-sizing | 10.0 4.0 -webkit- | 8.0 | 29.0 2.0 -moz- | 5.1 3.1 -webkit- | 9.5 |
Without the CSS3 box-sizing Property
默认情况,元素的宽高计算如下所示:
width + padding + border = actual width of an element
height + padding + border = actual height of an element
意及:当你设置元素的宽高时,元素常常呈现出比你设置的要大(因为元素的边框和内边距被增加到宽高之中)。
下列示例演示设置了相同宽高的两个 <div>
元素:
.div1 {
width: 300px;
height: 100px;
border: 1px solid blue;
}
.div2 {
width: 300px;
height: 100px;
padding: 50px;
border: 1px solid red;
}
<!DOCTYPE html>
<html>
<head>
<style>
.div1 {
width: 300px;
height: 100px;
border: 1px solid blue;
}
.div2 {
width: 300px;
height: 100px;
padding: 50px;
border: 1px solid red;
}
</style>
</head>
<body>
<div class="div1">This div is smaller (width is 300px and height is 100px).</div>
<br>
<div class="div2">This div is bigger (width is also 300px and height is 100px).</div>
</body>
</html>
以上两个 <div>
元素的大小是不同的(div2 有指定内边距)。
因此,很长时间以来,web 开发人员指定宽度值要比他们想要的值小,因为他们不得不扣除内边距和边框部分的宽度值。
在 CSS3 中,box-sizing 属性解决了该问题。
With the CSS3 box-sizing Property
CSS3 的 box-sizing 属性允许我们将内边距和边框包含在元素总宽高之内。
如果你对元素设置 box-sizing: border-box;,内边距和边框会包含在宽高之内,以下示例对 <div>
元素设置了 box-sizing: border-box;:
.div1 {
width: 300px;
height: 100px;
border: 1px solid blue;
box-sizing: border-box;
}
.div2 {
width: 300px;
height: 100px;
padding: 50px;
border: 1px solid red;
box-sizing: border-box;
}
<!DOCTYPE html>
<html>
<head>
<style>
.div1 {
width: 300px;
height: 100px;
border: 1px solid blue;
box-sizing: border-box;
}
.div2 {
width: 300px;
height: 100px;
padding: 50px;
border: 1px solid red;
box-sizing: border-box;
}
</style>
</head>
<body>
<div class="div1">Both divs are the same size now!</div>
<br>
<div class="div2">Hooray!</div>
</body>
</html>
鉴于使用 box-sizing: border-box; 的结果非常不错,许多开发人员想要他们的页面里的所有元素都遵循该方式。
下列代码确保将以这种更为直观的方式改变所有元素的大小。很多浏览器对很多表单元素已经使用 box-sizing: border-box;(但并不是所有的 - 原因在于 inputs
和 text areas
的宽度设置为 100% 时,它们看起来是不同的)。
* {
box-sizing: border-box;
}
<!DOCTYPE html>
<html>
<head>
<style>
body {
margin: 0;
}
* {
box-sizing: border-box;
}
input, textarea {
width: 100%;
}
</style>
</head>
<body>
<form action="http://www.w3schools.com/css/action_page.php">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br>
Comments:<br>
<textarea name="message" rows="5" cols="30"></textarea>
<br>
<br>
<input type="submit" value="Submit">
</form>
<p>
<strong>Tip:</strong> Try to remove the box-sizing property from the style element and look what happens. Notice that the width of input, textarea, and submit button will go outside of the screen.
</p>
</body>
</html>