问题
i'm trying to set some elements' width with percentage relative to grandparent elements' width. like this.
<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>
But i have no idea how to make this done, how can i make child elements refer directly to it's grandparent elements not direct parent elements? ( in this case if i set child elements width 50% it has to be 500px, not 1000px. )
are there possible ways to do this?
回答1:
You can use CSS custom properties, var() and calc() functions
.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>
回答2:
You can use absolute position to child element.
Apply this css:
.grand{width:1000px; overflow:hidden; position:relative;height:200px;}
.parent{width:2000px; }
.child1{float:left; width:50%; height:200px; background-color:blue; position:absolute; top:0; left:0;}
.child2{float:left; width:50%; height:200px; background-color:green; position:absolute; top:0; left:50%;}
回答3:
Please change it to:
.parent{width:2000px; position:relative} --> .parent{width:1000%; position:relative; display: inline;}
来源:https://stackoverflow.com/questions/48455590/how-to-set-width-relative-to-grandparent-elements-not-direct-parent-elements