简体   繁体   English

为什么高度100%在绝对定位的元素上起作用?

[英]Why does height 100% work on absolutely positioned element?

As far as I know for the height to work as percentage the container element must have a specific height mentioned. 据我所知,要使高度以百分比形式工作,容器元素必须具有指定的特定高度。 But this doesn't hold true for absolutely positioned element with the ancestor being relatively positioned. 但这对于祖先相对定位的绝对定位的元素并不适用。 Here is a working example of what I meant: 这是我的意思的工作示例:

 .container { width: 400px; background: cyan; text-align: right; position: relative; color: white; } .child { width: 90%; height: 100%; background: blue; } .absolute { position: absolute; } .second { margin-top: 30px; } 
 <div class="container"> <div class="child absolute">Absolute</div> one <br> two <br> three <br> one <br> two <br> three <br> </div> <div class="container second"> <div class="child">Static</div> one <br> two <br> three <br> one <br> two <br> three <br> </div> 

As you can see the absolutely placed div applied 100% height onto it but not the statically positioned div. 如您所见,绝对放置的div会应用100%的高度,而静态放置的div不会。 Why? 为什么?

From MDN 从MDN

relative This keyword lays out all elements as though the element were not positioned, and then adjusts the element's position, without changing layout (and thus leaving a gap for the element where it would have been had it not been positioned). relative这个关键字对所有元素进行布局,就像未放置元素一样,然后在不更改布局的情况下调整元素的位置(这样就可以在没有放置元素的情况下为元素留出空隙)。 The effect of position:relative on table-*-group, table-row, table-column, table-cell, and table-caption elements is undefined. position:相对于table-*-group,table-row,table-column,table-cell和table-caption元素的影响是不确定的。

Read more . 阅读更多 Is very nicely described. 描述得很好。

Here is a great read about the different position types: 是有关不同头寸类型的精彩读物:

Absolute is relative to the parent element and is not affected by other elements and are removed from the flow of the page ie you can see the list with one, two, three unaffected. 绝对相对于父元素,不受其他元素影响,并从页面流中删除,即您可以看到列表中的一,二,三不受影响。

It's height is 100% as .child specifies. 如.child指定的,其高度为100%。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM