0

Desired result

I have a container with fixed height. I want its content to be centerd like this:

But when the height of the container becomes smaller (or the amount of content becomes larger), then I want a scrollbar to appear like this:

Faulty implementation

Here's my implementation:

.Container {
  position: fixed;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100vh;
  
  overflow-y: auto;
  
  border: 10px dashed black;
  box-sizing: border-box;
  
  display: flex;
  align-items: center;
  justify-content: center;
}
<div class="Container">
  <ol class="Content">
    <li>Hello world.</li>
    <li>Hello world.</li>
    <li>Hello world.</li>
    <li>Hello world.</li>
    <li>Hello world.</li>
    <li>Hello world.</li>
    <li>Hello world.</li>
    <li>Hello world.</li>
    <li>Hello world.</li>
    <li>Hello world.</li>
    <li>Hello world.</li>
    <li>Hello world.</li>
    <li>Hello world.</li>
    <li>Hello world.</li>
    <li>Hello world.</li>
    <li>Hello world.</li>
    <li>Hello world.</li>
    <li>Hello world.</li>
    <li>Hello world.</li>
    <li>Hello world.</li>
  </ol>
</div>

The first case (enough height, no scrollbar) is all right. But with the second case (not enough height, scrollbar), the scrollbar behaves weirdly:

Note how the scrollbar is in the top position, and yet the top of the content appears cropped, and it's impossible to see the first line.

The bigger the difference between container height and content height is, the more content gets cropped.

I have identified that removing this line resolves the issue for the scrollbar case:

      align-items: center;

...but it breaks the vertical centering in the no-scrollbar layout.

This behavior is consistent across Chrome and Firefox.

Ugly workaround

My workaround is to move overflow-y: auto into the inner container like this:

.Content {
  max-height: 100%;
  overflow-y: auto;
}

But this moves the position of the scrollbar:

...which is exceptionally bad for tablets where the scrollbar is invisible and the area would seem unscrollabe.

Questions:

  1. Why does this happen?

    I mean, I understand that it happens due to vertical centering. The scrollbar now seems to control only 50% of the difference between the two heights.

    But why is it like that? Is there a standard that defines this? Is there practical benefit from it?

  2. How do I achieve desired result? Preferably, with minimal changes to the existing setup.

PS Here's a codepen to fiddle with if you prefer that: https://codepen.io/lolmaus/pen/rNzorxE (note that StackOverflow has built in Snippet feature that works like CodePen).

Andrey Mikhaylov - lolmaus
  • 23,107
  • 6
  • 84
  • 133

0 Answers0