我正在尝试设置一些元素的宽度相对于祖父母元素宽度的百分比。像这样。
<style>
.grand{width:1000px; overflow:hidden;}
.parent{width:2000px; position:relative}
.child1{float:left; width:50%; height:200px; background-color:blue;}
.child2{float:left; width:50%; height:200px; background-color:green;}
</style>
<div class="grand">
<div class="parent">
<div class="child1"></div>
<div class="child2"></div>
</div>
</div>
但我不知道如何做到这一点,如何使子元素直接引用它的祖父母元素而不是直接父元素? (在这种情况下,如果我将子元素宽度设置为 50%,则它必须为 500px,而不是 1000px。)
有可能的方法吗?
你可以使用CSS自定义属性, var() and calc()功能
.grand {
--main-width: 1000px;
width: 1000px;
overflow: hidden;
}
.parent {
width: calc(var(--main-width) * 2);
position: relative
}
.child1, .child2 {
float: left;
width: calc(var(--main-width) / 2);
height: 200px;
}
.child1 {
background-color: blue;
}
.child2 {
background-color: green;
}
<div class="grand">
<div class="parent">
<div class="child1"></div>
<div class="child2"></div>
</div>
</div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)