0

I have a container div that its content can grow vertically. I used overflow-y: auto for the container to make my page look good. But I need to place everything in the center when the content's height is smaller than the container's. So I used flexbox to do that. But the problem is that I can't scroll completely to see the top part of the contents.


Here is a simple example of the problematic code:

<html lang="en">
  <head>
    <style>
      .container {
        width: 20rem;
        height: 20rem;
        background-color: red;

        display: flex;
        justify-content: center;
        flex-direction: column;
        align-items: center;

        overflow-y: auto;

      }
      .child {
        width: 10rem;
        height: 40rem;
        background-color: blue;
        flex-shrink: 0;
      }
      .top {
        width: 1rem;
        height: 1rem;
        background-color: green;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <div class="child">
        <div class="top"></div>
      </div>
    </div>
  </body>
</html>
Navid Naseri
  • 106
  • 1
  • 10
  • If you first landed on this question, there is another question [here](https://stackoverflow.com/questions/33454533/cant-scroll-to-top-of-flex-item-that-is-overflowing-container) you might need to read through. – nibble Jun 19 '22 at 15:47

1 Answers1

3

One of the solutions to this problem is to use the reverse order of the elements in the flex-container, i.e. in your case, using flex-direction: column-reverse instead of flex-direction: column.

Example #1 below:

.container {
  width: 20rem;
  height: 20rem;
  background-color: red;
  display: flex;
  justify-content: center;
  flex-direction: column-reverse;
  align-items: center;
  overflow-y: auto;
}

.child {
  width: 10rem;
  min-height: 0;
  height: 40rem;
  background-color: blue;
  flex-shrink: 0;
  max-height: 150%;
}

.top {
  width: 1rem;
  height: 1rem;
  background-color: green;
}
<div class="container">
  <div class="child">
    <div class="top">test</div>
  </div>
</div>

The second solution is to consider using for center alignment, you can also use justify-content: space-between and pseudo-elements ::after and ::before.

Example #2 below:

.container {
  width: 20rem;
  height: 20rem;
  background-color: red;
  display: flex;
  justify-content: space-between;
  flex-direction: column;
  align-items: center;
  overflow-y: auto;
}

.container::before,
.container::after {
  content: '';
}

.child {
  width: 10rem;
  min-height: 0;
  height: 40rem;
  background-color: blue;
  flex-shrink: 0;
  max-height: 150%;
}

.top {
  width: 1rem;
  height: 1rem;
  background-color: green;
}
<div class="container">
  <div class="child">
    <div class="top">test222</div>
  </div>
</div>
Oleg Barabanov
  • 2,468
  • 2
  • 8
  • 17