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>
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>
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>
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.
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%;
}