html - CSS3 box-sizing 属性

标签 html css properties

我不明白应该如何使用 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/

相关文章:

javascript - 确定 JavaScript 属性是否定义了 getter 或 setter?

c# - => 运算符在属性中意味着什么?

Javascript 通知解决方案库 : desktop, 可听、弹出、标题栏闪烁等

javascript - 如何在文本输入中设置图标?

css - 相对于父 div 不显示代码

html - 无需滚动即可显示 iframe 的全部内容

c# - 类属性的名称到字符串

html - 使用 Bootstrap 去除网页右侧的空白区域

javascript - 使用下拉菜单链接的 Bootstrap 选项卡导航

javascript - 如何检测图像加载失败,如果失败,尝试重新加载直到成功?