0

I need to be able to set the height of an element in CSS or LESS dynamically.

I want sibling-2 to be 50% height of sibling-1.

<div class="sibling-1 dynamic-height"></div>
<span class="sibling-2"></span>
oygen
  • 467
  • 1
  • 7
  • 13
  • 1
    Can you post a code example? Providing more details will assist people with providing a useful answer. – j-petty Feb 06 '20 at 09:40
  • 1
    For clarification, are you looking for something like this? https://codepen.io/icansee-frontend/pen/BaNaZaK – Karl Feb 06 '20 at 09:49

3 Answers3

1

CSS grid can do this

.container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-auto-rows:1fr; /* This */
  border: 1px solid;
  margin:5px;
}

.sibling-1 {
  grid-row:span 2; /* and this will do the magic */
  background: blue;
  color:#fff;
}

.sibling-2 {
  background:red;
}
<div class="container">
  <div class="sibling-1 dynamic-height"> some text here</div>
  <span class="sibling-2"></span>
</div>

<div class="container">
  <div class="sibling-1 dynamic-height"> some <br>text <br>here</div>
  <span class="sibling-2"></span>
</div>

<div class="container">
  <div class="sibling-1 dynamic-height" style="height:200px;"> some <br>text <br>here</div>
  <span class="sibling-2"></span>
</div>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
0

This is not possible with native flexbox, however using the same techniques as this Q&A - One flex item sets the height limit for siblings it can be achieved.

.parent {
  display: flex;
  position: relative;
  border: 1px solid grey;
}

.sibling-1 {
  flex: 0 0 50%;
  height: 150px;
  background: lightblue;
  resize: vertical;
  overflow: auto;
}

.sibling-2 {
  position: absolute;
  left: 50%;
  height: 50%;
  background: lightgreen;
  width: 50%;
}
<div class="parent">
  <div class="sibling-1 dynamic-height"></div>
  <span class="sibling-2"></span>
</div>

Note: this is a little bit of a cheat in that the height of sibling-2 is not actually 50% of the sibling-1 but rather 50% of the height of the parent whose height is defined by sibling-1. It works but I'd suggest it's not really scalable or recommended for production purposes.

Paulie_D
  • 107,962
  • 13
  • 142
  • 161
-5

Simply edit your sibling-2 class like

.sibling-2{
    height: 50%;
}

This will work only if sibling-1 have a content or a fixed height. If not, you have to set it:

.sibling-1{
    height: 100vh;
}
.sibling-2{
    height: 50%;
}