面试题答案
一键面试1. content - box
- 宽度和高度计算:在
content - box
模式下,元素的宽度(width
)和高度(height
)仅包含内容区域。当设置width
和height
时,实际占据的空间会随着内边距(padding
)和边框(border
)的增加而增大。- 例如,设置一个块级元素
width: 200px; height: 100px; padding: 20px; border: 10px solid black;
,那么该元素在水平方向实际占据的空间为width + 2 * padding + 2 * border = 200 + 2 * 20 + 2 * 10 = 260px
,垂直方向为height + 2 * padding + 2 * border = 100 + 2 * 20 + 2 * 10 = 160px
。
- 例如,设置一个块级元素
- 实际布局应用场景:适用于需要精确控制内容区域大小,并且希望内边距和边框在内容区域之外增加整体尺寸的场景。比如,一个图片展示区域,希望图片始终保持设定的尺寸,而内边距和边框是额外增加的空间来美化展示效果。
2. border - box
- 宽度和高度计算:在
border - box
模式下,元素的宽度(width
)和高度(height
)包含了内容区域、内边距和边框。即设置的width
和height
值是最终元素占据的总宽度和总高度,内边距和边框会在这个设定的尺寸内分配空间。- 例如,同样设置一个块级元素
width: 200px; height: 100px; padding: 20px; border: 10px solid black;
,在border - box
模式下,内容区域的宽度为width - 2 * padding - 2 * border = 200 - 2 * 20 - 2 * 10 = 140px
,高度为height - 2 * padding - 2 * border = 100 - 2 * 20 - 2 * 10 = 40px
。
- 例如,同样设置一个块级元素
- 实际布局应用场景:适用于希望设置一个固定尺寸的容器,并且内边距和边框不会改变容器整体尺寸的场景。比如,导航栏的菜单项,希望菜单项始终保持一定的宽度和高度,内边距和边框在这个固定尺寸内调整,不会影响整个导航栏的布局。
示例代码
<!DOCTYPE html>
<html lang="en">
<head>
<style>
/* content - box 示例 */
.content - box {
box - sizing: content - box;
width: 200px;
height: 100px;
padding: 20px;
border: 10px solid black;
background - color: lightblue;
}
/* border - box 示例 */
.border - box {
box - sizing: border - box;
width: 200px;
height: 100px;
padding: 20px;
border: 10px solid black;
background - color: lightgreen;
margin - top: 20px;
}
</style>
</head>
<body>
<div class="content - box">content - box 模式</div>
<div class="border - box">border - box 模式</div>
</body>
</html>
在上述代码中,两个div
分别展示了content - box
和border - box
两种模式下不同的布局效果。可以通过浏览器查看实际占据空间的差异。