默認(rèn)情況下,在CSS框模型中肴裙,分配給元素的寬度和高度僅應(yīng)用于元素的內(nèi)容框涌乳。如果元素具有任何邊框或填充,則會(huì)將其添加到寬度和高度宛乃,以獲得在屏幕上呈現(xiàn)的框的大小蒸辆。這意味著當(dāng)您設(shè)置寬度和高度時(shí),您必須調(diào)整您給出的值以允許添加任何邊框或填充谆奥。
該box-sizing
屬性可用于調(diào)整此行為:
-
content-box
為您提供默認(rèn)的CSS框大小調(diào)整行為拂玻。如果將元素的寬度設(shè)置為100像素,則元素的內(nèi)容框?qū)?00像素寬檐蚜,并且任何邊框或填充的寬度將添加到最終渲染寬度。 -
border-box
告訴瀏覽器在您為元素的寬度和高度指定的值中考慮任何邊框和填充逢渔。如果將元素的寬度設(shè)置為100像素乡括,則100個(gè)像素將包含您添加的任何邊框或填充智厌,并且內(nèi)容框?qū)⒖s小以吸收該額外寬度。這通常會(huì)使元素的大小更容易敷扫。
句法
值
:content-box
元素的尺寸計(jì)算公式如下:width =內(nèi)容的寬度,height =內(nèi)容的高度绘迁。(邊框和填充不包括在計(jì)算中卒密。)
:border-box
元素的尺寸計(jì)算如下:width = border + padding +內(nèi)容的寬度,height = border + padding +內(nèi)容的高度哮奇。
例
這個(gè)例子展示了不同的box-sizing值如何改變其他兩個(gè)相同元素的渲染大小。
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 */
}