【问题标题】:Making an element 100% the width of its grandparent使元素 100% 为其祖父元素的宽度
【发布时间】:2019-05-25 22:03:30
【问题描述】:

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

【问题讨论】:

  • 请展示您的 HTML 示例,并清楚地解释哪些元素的行为应与您描述的一样。对于这样一个模糊的问题,我们无能为力。
  • 那么如果父母比祖父母更想做什么?水平滚动条?也许真实的例子会更有意义。
  • 也许真正的代码在这里会有所帮助....
  • 这里我写了两个可能的解决方案。希望对您有所帮助。

标签: javascript css sass


【解决方案1】:

解决方案 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>

【讨论】:

  • 不幸的是,这些解决方案只有在您可以修改祖父母时才有效。就我而言,不能保证祖父母有 position:relative 或一个共同的班级。不过感谢您的关注!
猜你喜欢
  • 1970-01-01
  • 2014-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-13
  • 1970-01-01
相关资源
最近更新 更多