Centered elements inside a flex container are growing and overflowing beyond top [duplicate]

You forgot nothing but you simply need to understand what is happening. First you made your wrapper to be 100% height of screen and then you made the box to be centred vertically and horizontally. When the box has a big height you will have something like this:

enter image description here

Now, when you add overflow-y: auto you will create a scroll that will start from the top of the wrapper until the bottom overflowed content. So it will be like this:

enter image description here

That’s why you are able to scroll to the bottom to see the bottom part and not able to see the top part.

To avoid this, use margin:auto to center your element and in this case we will have two situations:

  1. When box-height < wrapper-height we will have the space spread equally on each side because of the margin:auto thus your element will be centred like expected.
  2. When box-height > wrapper-height we will have the normal behavior and your element will overflow and his top edge will stick to the top edge of the wrapper.

enter image description here

You may also notice the same can happen horizontally that’s why I will use margin to center on both directions.

body,
html {
  height: 100%;
  width: 100%;
  margin: 0;
}

* {
  box-sizing: border-box;
}

#wrapper {
  background: grey;
  height: 100%;
  width: 100%;
  max-height: 100%;
  padding:30px 0;
  display: flex;
  overflow-y: auto;
}

#box {
  margin: auto;
  background: white;
  border: 1px solid #dfdfdf;
}
<div id="wrapper">
  <div id="box">
    First line
    <br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br>line<br> Last linje
  </div>
</div>

Leave a Comment