how to set width relative to grandparent elements not direct parent elements?

不问归期 提交于 2021-02-04 18:17:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!