使元素的宽度为其祖父母的宽度的100%

时间:2019-05-21 15:02:12

标签: javascript css sass

我正在尝试使一个元素动态匹配其祖父母的宽度(使用“ width: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
}

1 个答案:

答案 0 :(得分:0)

解决方案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>
相关问题