我试图用相对于祖 parent 元素宽度的百分比来设置一些元素的宽度。像这样。
<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 custom properties , var()
和 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>
关于javascript - 如何设置相对于祖 parent 元素而不是直接父元素的宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48455590/