Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 716
James David Deann Avatar asked Jan 26 '18 03:01

James David Deann


2 Answers

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>
like image 88
guest271314 Avatar answered Sep 19 '22 20:09

guest271314


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%;}
like image 27
Nidhi Avatar answered Sep 19 '22 20:09

Nidhi