user626528
user626528

Reputation: 14418

Setting width relatively to the size of the grandparent div

I have the structure that currently looks approximately like the snippet below; how can I make div2 to take the width 50% of its grandparent div, rather than 50% of its immediate parent?

<div id="grandParent" style="width: 100%; display: flex; flex-direction: row; flex-wrap: nowrap; background-color: yellow; border-color: yellow">
  <div id="div1" style="width: 100px; background-color: aqua">
    div1
  </div>
  <div id="parent" style="width: 100%; background-color: green">
    parent<br>
    <div id="div2" style="width: 50%; background-color: fuchsia; margin: 0 auto;">
      div2
    </div>
  </div>
</div>

Upvotes: 0

Views: 153

Answers (1)

Temani Afif
Temani Afif

Reputation: 273031

We can do some maths. The width of the parent is P - 100px and you need to have P/2 so if you do X/2 + 50px where X = P - 100px you will have P/2. Also better use flex-grow:1 instead of width:100% to avoid the shrink effect and have the first div always at 100px

console.log($('#div2').width())
console.log($('#grandParent').width())
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="grandParent" style=" display: flex; flex-direction: row; flex-wrap: nowrap; background-color: yellow; border-color: yellow">
  <div id="div1" style="width: 100px; background-color: aqua">
    div1
  </div>
  <div id="parent" style="flex-grow:1; background-color: green">
    parent<br>
    <div id="div2" style="width: calc(50% + 50px); background-color: fuchsia; margin: 0 auto;">
      div2
    </div>
  </div>
</div>

You can consider the use of CSS variable to make this easier:

console.log($('#div2').width())
console.log($('#grandParent').width())
:root {
 --w:100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="grandParent" style="display: flex; flex-direction: row; flex-wrap: nowrap; background-color: yellow; border-color: yellow">
  <div id="div1" style="width: var(--w); background-color: aqua">
    div1
  </div>
  <div id="parent" style="flex-grow:1;background-color: green">
    parent<br>
    <div id="div2" style="width: calc(50% + var(--w)/2); background-color: fuchsia; margin: 0 auto;">
      div2
    </div>
  </div>
</div>

Upvotes: 1

Related Questions