-1

I am trying to stack two elements vertically with each element having dynamic heights.

The first element will be fixed at the top and the second element will have overflow and I want it to be scrollable but the height of the first element is unknown.

So lets say the first element could be a height of anywhere between 100 and 150 pixels. The height of the second element would need to be 100% minus the height of the first element.

So how do I have both elements to be dynamic without having to fix the height of the first element.

#element-1
    width: 100%
    min-width: 300px
    height: 150px

#element-2
    width: 100%
    min-width: 300px
    height: calc(100% - 150px)
    overflow-y: auto
    -webkit-overflow-scrolling: touch

I have this and it works but if element 1 is less than 150px then I have this unwanted dead space between the two elements.

1 Answers1

0

In your case, CSS flexbox will be helpful in stacking elements vertically with dynamic heights.

So, to do that you need to add display: flex; and flex-direction: column; properties to the parent element of your dynamic elements, which you want to stack vertically with dynamic heights.

parent-element {
  display: flex;
  flex-direction: column;
}

Working Sample:

div {
  padding: 2em;
}

.container {
  text-align: center;
  display: flex;
  flex-direction: column;
  background-color: lightgrey;
  width: 400px;
  height: 350px;
  margin: 10px auto;
}

.element-1 {
  background-color: lightgreen;
  height: 100px;
}

.element-2 {
  background-color: lightblue;
  height: 100%;
}
<div class="container">
  <div class="element-1">Fixed Element</div>
  <div class="element-2">Dynamic Element</div>
</div>
Kumara
  • 480
  • 1
  • 4
  • 13