javascript - 使元素的宽度达到其祖父元素的 100%

标签 javascript css sass

我试图让一个元素动态匹配其祖父元素的宽度(使用“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/

相关文章:

javascript - 当我按下任何地方时如何关闭侧边栏

javascript - 表上的 jquery 选择器

javascript - 函数可以在 javascript 中引用自身吗?

html - 如何让图片不滚动?

css - 为什么期望 1px 粗体为背景颜色?

html - 在初始规则集中包含伪类样式

javascript - 服务器中的 ddl 未更新 - asp.net

javascript - 如何让眼睛跟随div之外的鼠标

sass - 配置 "Live Sass Compiler"(VSCode模块)

javascript - 当这些样式移入 .CSS 文件时,直接应用于元素的样式将丢失