Im trying to put 3 divs in a parent div, the parent div has a fixed height (lets say 300px). The middle div has a variable height, i want the other 2 divs to dynamically adjust their heights in order to always have 300px in total height. Is there a solution for that?
Asked
Active
Viewed 345 times
-1
-
Just use display:flex; it will help you. and put min height 300px don't contraint others div height. – ExploreNav Jul 27 '21 at 09:05
-
@AndrewL64 Not really – ilpianoforte Jul 27 '21 at 09:29
3 Answers
0
.parentDiv{
background-color: #999;
display:flex;
height:300px;
justify-content: space-between;
align-items: stretch;
}
.childDiv{
background-color: #fff;
border: 1px solid red;
flex: 1 1 0;
}
<div class="parentDiv">
<div class="childDiv"></div>
<div class="childDiv">
Hi, this is default text. It can be increase accordingly
</div>
<div class="childDiv"></div>
</div>

ExploreNav
- 386
- 2
- 11
0
Yes you can get the height of your parent element & the height of your middle element in javascript, then you select the other two divs and give them for example a percentage of what's left, to get the height of an element: document.getElementById('myID'). offsetHeight
to set the height document.getElementById("otherID").style.height = what you want

Moon Days
- 19
- 3
-2
One simple way to achieve this is with flex
. You have a single-dimensional layout, so it's the perfect fit.
*edit - looking at other answers, I might've misunderstood you and wrote about a vertical axis, not the horizontal. it wasn't specifically mentioned.
.parent {
/* We use vertical flex direction so we can utilize the flex property */
display: flex;
flex-direction: column;
height: 300px;
}
.children {
/* All should grow or shrink and take as much as possible.*/
flex: 1 1 auto;
background: yellow;
}
.auto {
/* No need to grow or shink specifically.*/
flex-grow: 0;
background: red;
color: white;
}
<h2>One line text:</h2>
<div class="parent">
<div class="children"></div>
<div class="children auto"><p>I am a paragraph.</p></div>
<div class="children"></div>
</div>
<h2>Long text:</h2>
<div class="parent">
<div class="children"></div>
<div class="children auto"><p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p></div>
<div class="children"></div>
</div>

Alex Dimitrov
- 52
- 4
-
Thanks for the answer, it really helped. Is there a way that i can always keep the vertical center of the middle div at the vertical center of the parent div? – ilpianoforte Jul 27 '21 at 09:32