CSS 的 box-sizing 属性指定了元素的 width 和 height 如何计算。
box-sizing 属性让我们控制盒子模型的工作方式。它允许我们将 padding 和 border 包含在元素的整体 width 和 height 中。
根据盒子模型,网页上的每个元素都被视为一个矩形框。下图显示了盒子模型的布局。
CSS box-sizing 语法
box-sizing 属性的语法如下:
box-sizing: content-box | border-box | initial | inherit;
这里,
content-box:根据元素的內容定义width和height,不包括padding和border。border-box:根据边框定义width和height,包括padding和border。initial:设置为默认值,即content-box。inherit:继承父元素的值。
无 Box-sizing 时的宽度和高度
默认情况下,width 和 height 属性应用于元素的內容。实际的 width 和 height 计算如下:
actual width: border-left + padding-left + width + padding-right + border-right
actual height: border-top + padding-top + height + padding-bottom + border-bottom
添加 padding 和 border 后,这会导致 width 和 height 大于实际指定的数值。
让我们看一个例子,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="style.css" />
<title>CSS box-model</title>
</head>
<body>
<div>
This div element has a width of 300px and a height of 200px. By
default, the width and height are applied to the content of an element
i.e. box-sizing is set to content-box.
</div>
</body>
</html>
div {
width: 300px;
height: 200px;
padding: 20px;
border: 10px solid black;
margin: 20px;
/* default value */
box-sizing: content-box;
background-color: greenyellow;
/* clips the background color to content only */
background-clip: content-box;
}
浏览器输出
在上面的示例中,尽管我们将 width 设置为 300px,height 设置为 200px,但实际渲染的 width 和 height 为:
actual width = 10px + 20px + 300px + 20px + 10px
actual height = 10px + 20px + 200px + 20px + 10px
因此,实际的 width 和 height 分别设置为 360px 和 260px。
有 Box-sizing 时的宽度和高度
box-sizing 属性的 border-box 值允许我们将 padding 和 border 包含在指定的 width 和 height 值中。例如:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="style.css" />
<title>CSS box-model</title>
</head>
<body>
<div>
This div element has a width of 300px and a height of 200px. By
default, the width and height are applied to the content of an
element i.e. box-sizing is set to content-box.
</div>
</body>
</html>
div {
width: 300px;
height: 200px;
padding: 20px;
border: 10px solid black;
margin: 20px;
box-sizing: border-box;
background-color: greenyellow;
/* clips the background color to content only */
background-clip: content-box;
}
浏览器输出
在上面的示例中,box-sizing: border-box 允许将 padding 和 border 包含在指定的 width 和 height 中。
因此,div 的 width 和 height 将精确地保持为 300px 和 200px。
开发人员通常更喜欢使用 border-box 值,因为它有助于控制元素的大小,从而为设计提供一致且可预测的结果。
注意:我们可以使用通用选择器 (*) 将 box-sizing 设置为所有元素的 border-box。例如:
* {
box-sizing: border-box;
}