如何使父 div 的固定 div 宽度本身以百分比定义?

How to make fixed div width of parent div, which itself is defined in percentage?

我在固定 div 其父元素的宽度时遇到问题,它本身是相对于另一个 div 定义的。

一开始可能不太清楚,所以这里有一段代码可以说明情况:

HTML

<div class="grandparent">
    <div class="parent">
        <div class="fixed"></div>
    </div>
</div>

CSS

.grandparent {
     width:100px;
     position:relative;
 }

.parent {
     width:70%;
     position:relative;
 }

.fixed {
     width:100%;
     position:fixed;   /* This div must be fixed and have 100% width relative to parent */
 }

这里是JSFiddle.

.fixed div 有什么方法可以在固定位置的同时继承其父级的宽度吗?

谢谢。

使用 postion: absolute 而不是 position: fixed

绝对定位适用于第一个相对父级。 固定适用于 window.

然后,您可以使用 topleftrightbottom 属性将 div 相对于其父级放置在视口中。

Fiddle: https://jsfiddle.net/k0vndvzj/3/

position: fixed 是相对于 window 视口的,只需从 .fixed {...} 中删除 position: fixed; 就可以了