我不明白应该如何使用 box-sizing 属性。因为:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
div.container
{
width:10em;
border:1em solid;
}
div.box
{
box-sizing:border-box;
-moz-box-sizing:border-box; /* Firefox */
-webkit-box-sizing:border-box; /* Safari */
width:50%;
border:1em solid red;
float:left;
}
</style>
</head>
<body>
<div class="container">
<div class="box">1</div>
<div class="box">2</div>
</div>
</body>
</html>
等同于:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
div.container
{
width:10em;
border:1em solid;
}
div.box
{
width:3em;
border:1em solid red;
float:left;
}
</style>
</head>
<body>
<div class="container">
<div class="box">1</div>
<div class="box">2</div>
</div>
</body>
</html>
那么我应该在什么时候使用那个属性,而那个属性到底该做什么呢?我使用了来自 w3 http://www.w3schools.com/cssref/css3_pr_box-sizing.asp 的示例
最佳答案
box-sizing: border-box
当您无法根据框的边距、边框和填充指定确切的内容宽度时最有用,因为您事先不知道(并且无法控制)这些值是什么。
在你的第一个例子中,如果你不知道盒子里有多少填充或者它的边框有多粗,让它使用边框模型允许你设置 width: 50%
以确保盒子始终占据其容器宽度的 50%,无论边框和填充如何。在第二个例子中,如果你设置了 width: 50%
那就是内容的宽度;边框和填充会添加到它,导致它实际扩展超过其容器宽度的 50%。
关于html - CSS3 box-sizing 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12195707/