为什么`height:100%`会为网格项的子标签赋值'work'? [英] Why does `height: 100%` value 'work' for child tags of grid-items?
问题描述
考虑一下:
#grid-container {
display: grid;
height: 200px;
grid-template-columns: repeat(2, 1fr);
grid-template-rows: repeat(2, 1fr);
}
.grid-item > p {
height: 100%;
}
<div id="grid-container" style="display: grid">
<div class="grid-item">
<p>I am p.</p>
</div>
<div class="grid-item">
<p>I am p.</p>
</div>
<div class="grid-item">
<p>I am p.</p>
</div>
<div class="grid-item">
<p>I am p.</p>
</div>
</div>
由于CSS行:
.grid-item > p {
height: 100%;
}
p
标签的高度与网格项目的高度相同.太好了,因为这就是我想要的.我的问题是,这如何运作?
The p
tags have the same height as the grid-items. This is great, as this is what I want. My question is, how is this working?
我认为,如果未明确指定父元素/包含块的 height
(肯定是网格项目,此处为 height:auto;
),则%
(在子元素上)将不起作用(而将使用类似 height:auto
的东西).
I thought that if the parent element/containing-block's height
wasn't specified explicitly (surely grid-items, here, have height: auto;
) then %
(on the child element) won't work (and something like height: auto
will be used instead).
此外,我知道/认为如果父母的位置绝对正确,则%
将起作用(返回父母实际 height
的百分比值).
Additionally, I know/think that if the parent is absolutely positioned, %
will work (return a percentage value of what parent's actual height
is).
什么使%
对网格项的子代起作用?
What is making %
work for children of grid-items?
推荐答案
这与网格项目的 stretch
默认对齐方式有关.
This is related to the stretch
default alignment of grid item.
注意:由于仅使用确定大小的公式(例如拉伸拟合公式)也是确定的,因此被拉伸的网格项目的大小也被认为是确定的. 参考
如您所见,大小是确定的,因此可以用作百分比的参考.
As you can see, the size is definite so can be used as reference for percentage.
flexbox的逻辑相同:
Same logic for flexbox:
如果flex项具有align-self:拉伸,对其内容进行重做布局,则将此使用的大小视为其确定的交叉大小,以便可以解决百分比大小的子项
参考
具有非直观百分比行为的相关问题: https://stackoverflow.com/a/52137966/8620333
Related question with non-intuive percentage behavior: https://stackoverflow.com/a/52137966/8620333
这篇关于为什么`height:100%`会为网格项的子标签赋值'work'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!