首页 > 解决方案 > 使元素 100% 为其祖父元素的宽度

问题描述

我正在尝试使元素动态匹配其祖父母的宽度(使用“宽度:100%”)。我不能修改祖父母,因为有问题的元素可以插入到一堆不同的地方,所有这些地方都有不同的祖父母元素。有没有办法使用 CSS 或 SCSS 使元素与其祖父母的宽度相匹配?

我也不能只使父宽度:100% 和元素宽度:100%,因为这会破坏其他东西。

已经发布的其他解决方案依赖于能够修改祖父母,并且在这种情况下不起作用。

<Grandparent>     //Can't modify grandparent
   <Parent>       //Width is different to that of the grandparent
      <Element/>  
   <Parent/>
<Grandparent/>
Parent {
   width:auto;
}
Element {
   width:100%; //This makes the element the same width as the Parent instead of the Grandparent
}

标签: javascriptcsssass

解决方案


解决方案 1:将绝对位置和宽度 100% 添加到孩子,没有位置到父级和相对于祖父母的位置:

<div class="grandparent"> GrandParent
    <div class="parent"> Parent
        <div class="child"> Child</div>
    </div>
</div>

<style>
    .grandparent {
        position: relative;
        width: 300px;
        background: orange;
    }

    .parent {
        width: 150px;
        background: yellow;
    }

    .child {
        position: absolute;
        width: 100%;
        background: lightgrey;
    }
</style>

解决方案2:创建一个类并将其添加到祖父母和孩子:

<div class="grandparent common-width"> GrandParent
    <div class="parent"> Parent
        <div class="child common-width"> Child</div>
    </div>
</div>

<style>
    .grandparent {
        width: 300px;
        background: orange;
    }

    .parent {
        width: 150px;
        background: yellow;
    }

    .child {
        background: lightgrey;
    }

    .common-width {
        width: 240px;
    }
</style>

推荐阅读