javascript - 使元素 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
}
解决方案
解决方案 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>
推荐阅读
- regex - 匹配除 3 个特定数字之外的所有 5 位数字 - 没有负面的后视
- google-cloud-datastore - 如何获得客观化参考(参考
) 在对 appengine 数据存储区执行查询时对象到实体? - java - 127.0.0.1 与 localhost - Spring Security 登录问题
- java - CRUB,前端认证问题,spring security
- javascript - 不和谐机器人错误类型错误:无法读取未定义的属性“名称”
- python - 在不退出程序的情况下引发异常
- linux - 为什么某些应用程序的多个窗口共享相同的pid?
- amazon-web-services - 如何在不复制的情况下在 S3 中创建文件
- .net - 有没有一种简单的方法可以在 Visual Studio 中回滚项目的 .Net 版本?
- python - Python:绘制数据框中每个组的百分比