包含塊:指元素最近的祖先塊元素(inline-block, block 或 list-item 元素)的內(nèi)容區(qū)。
包含塊的影響
元素的尺寸及位置,常常會(huì)受它的包含塊所影響。
如 width, height, padding, margin,left,right,top,bottom 等屬性,當(dāng)其值為百分比時(shí),元素的這些值,就是通過包含塊計(jì)算得出。
如何確定元素的包含塊?
確定一個(gè)元素的包含塊的過程完全依賴于這個(gè)元素的 position 屬性:
如果 position 屬性為
static、relative或sticky,包含塊可能由它的最近的祖先塊元素的內(nèi)容區(qū)的邊緣組成,也可能會(huì)建立格式化上下文。如果 position 屬性為
absolute,包含塊就是由它的最近的 position 的值不是static(也就是值為fixed,absolute,relative或sticky)的祖先元素的內(nèi)邊距區(qū)的邊緣組成。如果 position 屬性是
fixed,在連續(xù)媒體的情況下(continuous media)包含塊是 viewport ,在分頁媒體(paged media) 下的情況下包含塊是分頁區(qū)域(page area)。-
如果 position 屬性是
absolute或fixed,包含塊也可能是由滿足以下條件的最近父級(jí)元素的內(nèi)邊距區(qū)的邊緣組成的:- transform 或 perspective 的值不是
none - will-change 的值是
transform或perspective - filter 的值不是
none或 will-change 的值是filter(只在 Firefox 下生效). - contain 的值是
paint(例如: contain: paint;)
- transform 或 perspective 的值不是
通過包含塊計(jì)算元素屬性的百分比值
如果某些屬性被賦予一個(gè)百分值的話,它的計(jì)算值是由這個(gè)元素的包含塊計(jì)算而來的。這些屬性包括盒模型屬性和偏移屬性:
要計(jì)算 height top 及 bottom 中的百分值,是通過包含塊的 height 的值。如果包含塊的 height 值會(huì)根據(jù)它的內(nèi)容變化,而且包含塊的 position 屬性的值被賦予 relative 或 static ,那么,這些值的計(jì)算值為 auto。
要計(jì)算 width, left, right, padding, margin 這些屬性由包含塊的 width 屬性的值來計(jì)算它的百分值。
<body>
<section>
<p></p>
</section>
</body>
例 1
section {
display: block;
width: 400px;
height: 160px;
background: lightgray;
}
p {
width: 50%; /* == 400px * .5 = 200px */
height: 25%; /* == 160px * .25 = 40px */
margin: 5%; /* == 400px * .05 = 20px */
padding: 5%; /* == 400px * .05 = 20px */
background: cyan;
}
例 2
section {
display: inline;
background: lightgray;
}
p {
width: 50%; /* == body 寬度的一半 */
height: 200px; /* 使用百分比將會(huì)計(jì)算為 0 */
background: cyan;
}
例 3
section {
position: absolute;
left: 30px;
top: 30px;
width: 400px;
height: 160px;
padding: 30px 20px;
background: lightgray;
}
p {
position: absolute;
width: 50%; /* == (400px + 20px + 20px) * .5 = 220px */
height: 25%; /* == (160px + 30px + 30px) * .25 = 55px */
margin: 5%; /* == (400px + 20px + 20px) * .05 = 22px */
padding: 5%; /* == (400px + 20px + 20px) * .05 = 22px */
background: cyan;
}
例 4
section {
width: 400px;
height: 480px;
margin: 30px;
padding: 15px;
background: lightgray;
}
p {
position: fixed;
width: 50%; /* == (50vw - (width of vertical scrollbar)) */
height: 50%; /* == (50vh - (height of horizontal scrollbar)) */
margin: 5%; /* == (5vw - (width of vertical scrollbar)) */
padding: 5%; /* == (5vw - (width of vertical scrollbar)) */
background: cyan;
}
例 5
section {
transform: rotate(0deg);
width: 400px;
height: 160px;
background: lightgray;
}
p {
position: absolute;
left: 80px;
top: 30px;
width: 50%; /* == 200px */
height: 25%; /* == 40px */
margin: 5%; /* == 20px */
padding: 5%; /* == 20px */
background: cyan;
}