Guru Prasad
Guru Prasad

Reputation: 4223

Scrollable element with flex pushing other elements out as it grows

I'm trying to create a page with the following layout:

+-------------------------------------------------------+
|                                                       |
|                           nav                         |
|                                                       |
+-------------------------------------------------------+
|                                                       |
|         content that should not scroll (fixed)        |
|                                                       |
+-------------------------------------------------------+
|                                                       |
|                                                       |
|                    Scrollable content                 |
|                taking up remaining height             |
|                                                       |
|                                                       |
|                                                       |
+-------------------------------------------------------+

Since the scrollable content needs to take up 'remaining height', I decided to try and use display: flex to try and solve this.

I added the following class to all elements from the scrollable content up to the first element (#app):

.flex {
  display: flex;
  flex-direction: column;
  min-height: 0;
}

The scrollable element itself has the additional overflow-y: auto; CSS property.

The top #app element has the following properties, most importantly, the height.

#app {
  position: absolute;
  top: 0;
  bottom: 0;
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;

  display: flex;
  flex-direction: column;
}

With this setup, I find that as the scrollable content grows, the nav and fixed content start to get pushed up further and further.

What is causing this and how can I prevent this? I simply want a page with some fixed content and an element that takes up the remaining height. Here's a codepen of my page

Upvotes: 0

Views: 665

Answers (1)

Piotr Wicijowski
Piotr Wicijowski

Reputation: 2115

First of all, with your approach of having everything in flex containers, using display: fixed on the navbar is doing more harm than good, since only the last div will be scrollable by itself, the navbar will stay in place regardless of the scroll. Once the navbar is display: block, then it is no longer taken out of regular layout context and its parent flex container can take its height into regular calculations. Additionally, by default, flex children have a value of flex-shrink set to 1, which means that the height of your tabs container will shrink once the total height of all flex children will exceed the height of flex container. Setting it to 0 prevents that problem. The end result with all the above fixes can be found in the forked codepen.

Upvotes: 1

Related Questions