为什么当您使用 position:relative at div 高度百分比时不起作用?
Why when you are using position:relative at div height in percent does not work?
为什么当 div 相对位置没有父级时 div 高度百分比不起作用?如果绝对位置有效
<div style="position: relative;
width:50%;
height: 50%;
background-color:black;">
</div>
相对位置意味着它将相对于其父项的正常位置进行定位。如果您的 div 没有固定高度的父项,那么您的 div 不知道它必须有多大,如果它的百分比,它没有相关的父项。
作为一个直接的结果,百分比的顶部也没有任何影响。
另一方面,position absolute 将相对于最近定位的祖先进行定位。然而;如果绝对定位元素没有定位的祖先,它使用文档主体,这就是它适用于您的原因。
The percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the value computes to 'auto'.
因此,当您设置 position: relative
并且在这种情况下,未指定父项的高度时,它会被视为 height: auto
。
一个绝对定位的元素,假设没有其他包含块阻挡,将视口作为其包含块,并且具有已知的高度。
为什么当 div 相对位置没有父级时 div 高度百分比不起作用?如果绝对位置有效
<div style="position: relative;
width:50%;
height: 50%;
background-color:black;">
</div>
相对位置意味着它将相对于其父项的正常位置进行定位。如果您的 div 没有固定高度的父项,那么您的 div 不知道它必须有多大,如果它的百分比,它没有相关的父项。
作为一个直接的结果,百分比的顶部也没有任何影响。
另一方面,position absolute 将相对于最近定位的祖先进行定位。然而;如果绝对定位元素没有定位的祖先,它使用文档主体,这就是它适用于您的原因。
The percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the value computes to 'auto'.
因此,当您设置 position: relative
并且在这种情况下,未指定父项的高度时,它会被视为 height: auto
。
一个绝对定位的元素,假设没有其他包含块阻挡,将视口作为其包含块,并且具有已知的高度。