我试图让一个元素动态匹配其祖父元素的宽度(使用“width: 100%”)。我不能修改祖 parent ,因为有问题的元素可以插入到一堆不同的地方,所有地方都有不同的祖 parent 元素。有没有办法使用 CSS 或 SCSS 使元素与其祖 parent 的宽度相匹配?
我也不能只设置父宽度:100% 和元素宽度:100%,因为那样会破坏其他东西。
已经发布的其他解决方案依赖于能够修改祖 parent ,在这种情况下不起作用。
<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:给 child 添加绝对位置和宽度 100%,没有给 parent 的位置和相对于祖 parent 的位置:
<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:创建一个类并将其添加到祖 parent 和 child 中:
<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>
关于javascript - 使元素的宽度达到其祖父元素的 100%,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56241183/