-1

Given the following snippet: http://jsfiddle.net/8wy1mku2/

.black {
  width: 200px;
  height: 100px;
  background: black;
}

.grey {
  width: 180px;
  height: 100%;
  background: grey;
}

.red {
  width: 160px;
  height: 20px;
  background: red;
}

.blue {
  width: 140px;
  height: 100%;
  background: blue;
}
<div class="black">
  <div class="grey">
    <div class="red">red</div>
    <div class="blue">blue</div>
  </div>
</div>

How can I make the blue child with height 100% respect the space of the red child?

I want the blue box to automatically resize to be of size 100% minus the size of the red box.

Please help!

an.dr.eas.k
  • 151
  • 8

2 Answers2

0

You can use the calc function. Like this:

Syntax

height: calc(100% - heightOfTheRedBox);

.black {
  width: 200px;
  height: 100px;
  background: black;
}

.grey {
  width: 180px;
  height: 100%;
  background: grey;
}

.red {
  width: 160px;
  height: 20px;
  background: red;
}

.blue {
  width: 140px;
  height: calc(100% - 20px);
  background: blue;
}
<div class="black">
  <div class="grey">
    <div class="red">red</div>
    <div class="blue">blue</div>
  </div>
</div>
Manas Khandelwal
  • 3,790
  • 2
  • 11
  • 24
  • what else can you think of? Why doesn't the blue box know the available height itself? – an.dr.eas.k Jun 23 '21 at 14:57
  • @an.dr.eas.k There are always many ways to achieve a single thing in CSS. You can use FlexBox, Grid, You can even use JavaScript, display table, hardcoded value, etc... – Manas Khandelwal Jun 23 '21 at 15:04
0

You should use flex on the grey box, then you can use flex grow on the blue box:

.black {
  width: 200px;
  height: 100px;
  background: black;
}

.grey {
  width: 180px;
  height: 100%;
  background: grey;
  display: flex;
  flex-direction: column;
}

.red {
  width: 160px;
  height: 20px;
  background: red;
}

.blue {
  width: 140px;
  background: blue;
  flex-grow: 1;
}
<div class="black">
  <div class="grey">
    <div class="red">red</div>
    <div class="blue">blue</div>
  </div>
</div>
Pete
  • 57,112
  • 28
  • 117
  • 166
  • yep! like that. For some reason I had to change reds height to min-height:20px, because it got reduced to 18px. Why? Is it possible to do that in the definition of grey? – an.dr.eas.k Jun 23 '21 at 15:10
  • flex calculates height based on content - you can use min height to make sure it has a minimum of 20px or try `flex-basis: 20px` – Pete Jun 23 '21 at 15:12
  • right: all your answers helped me figuring out more about that. A flex-shrink: 0 also hinders shrinking... – an.dr.eas.k Jun 24 '21 at 06:54
  • I am now using a combination of this flex setting and display: grid with grid-row-template: auto 1fr – an.dr.eas.k Jun 24 '21 at 06:55