试一试
box-sizing: content-box;
width: 100%;
box-sizing: content-box;
width: 100%;
border: solid #5b6dcd 10px;
padding: 5px;
box-sizing: border-box;
width: 100%;
border: solid #5b6dcd 10px;
padding: 5px;
<section id="default-example">
<div id="example-element-parent">
<p>Parent container</p>
<div class="transition-all" id="example-element">
<p>Child container</p>
</div>
</div>
</section>
#example-element-parent {
width: 220px;
height: 200px;
border: solid 10px #ffc129;
margin: 0.8em;
}
#example-element {
height: 60px;
margin: 2em auto;
background-color: rgb(81 81 81 / 0.6);
}
#example-element > p {
margin: 0;
}
在 CSS 盒模型中,默认情况下,您为元素指定的 width 和 height 仅应用于元素的内容盒。如果元素有任何边框或内边距,这些值将添加到 width 和 height 中,以得出屏幕上渲染的盒子的最终尺寸。这意味着当您设置 width 和 height 时,必须调整您给定的值以适应可能添加的任何边框或内边距。例如,如果您有四个 width: 25%; 的盒子,如果其中任何一个有左或右内边距或左或右边框,它们默认情况下将无法在父容器的限制内排在一行。
box-sizing 属性可用于调整此行为。
-
content-box赋予您默认的 CSS 盒模型行为。如果您将元素的宽度设置为 100 像素,那么元素的内容盒将是 100 像素宽,任何边框或内边距的宽度都将添加到最终渲染宽度中,使元素宽度超过 100 像素。 -
border-box告诉浏览器在您为元素的宽度和高度指定的值中考虑任何边框和内边距。如果您将元素的宽度设置为 100 像素,这 100 像素将包括您添加的任何边框或内边距,内容盒将收缩以吸收额外的宽度。这通常会使元素尺寸的设定变得容易得多。box-sizing: border-box是浏览器对<table>、<select>和<button>元素,以及类型为radio、checkbox、reset、button、submit、color或search的<input>元素使用的默认样式。
注意:将 box-sizing 设置为 border-box 以布局元素通常很有用。这使得处理元素尺寸变得容易得多,并且通常可以消除您在布局内容时可能遇到的许多陷阱。另一方面,当使用 position: relative 或 position: absolute 时,使用 box-sizing: content-box 允许定位值相对于内容,并且独立于边框和内边距尺寸的变化,这有时是可取的。
语法
box-sizing: border-box;
box-sizing: content-box;
/* Global values */
box-sizing: inherit;
box-sizing: initial;
box-sizing: revert;
box-sizing: revert-layer;
box-sizing: unset;
box-sizing 属性由从以下值列表中选择的单个关键字指定。
值
content-box-
这是 CSS 标准中指定的初始默认值。
width和height属性包含内容,但不包括内边距、边框或外边距。例如,.box {width: 350px; border: 10px solid black;}将渲染一个 370 像素宽的盒子。在这里,元素的尺寸计算方式为:宽度 = 内容的宽度,高度 = 内容的高度。(边框和内边距不包含在计算中。)
border-box-
width和height属性包括内容、内边距和边框,但不包括外边距。请注意,内边距和边框将在盒子内部。例如,.box {width: 350px; border: 10px solid black;}将渲染一个 350 像素宽的盒子,其中内容区域为 330 像素宽。内容盒不能为负数且向下取整为 0,这使得无法使用border-box使元素消失。在这里,元素的尺寸计算方式为:宽度 = 边框 + 内边距 + 内容的宽度,高度 = 边框 + 内边距 + 内容的高度。
正式定义
正式语法
box-sizing =
content-box |
border-box
示例
使用 content-box 和 border-box 的盒子尺寸
此示例展示了不同的 box-sizing 值如何改变两个其他方面相同的元素的渲染尺寸。
HTML
<div class="content-box">Content box</div>
<br />
<div class="border-box">Border box</div>
CSS
div {
width: 160px;
height: 80px;
padding: 20px;
border: 8px solid red;
background: yellow;
}
.content-box {
box-sizing: content-box;
/* Total width: 160px + (2 * 20px) + (2 * 8px) = 216px
Total height: 80px + (2 * 20px) + (2 * 8px) = 136px
Content box width: 160px
Content box height: 80px */
}
.border-box {
box-sizing: border-box;
/* Total width: 160px
Total height: 80px
Content box width: 160px - (2 * 20px) - (2 * 8px) = 104px
Content box height: 80px - (2 * 20px) - (2 * 8px) = 24px */
}
结果
规范
| 规范 |
|---|
| CSS Box Sizing Module Level 3 # box-sizing |
浏览器兼容性
加载中…