Centered elements inside a flex container are growing and overflowing beyond top
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:
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:
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:
- When
box-height < wrapper-height
we will have the space spread equally on each side because of themargin:auto
thus your element will be centred like expected. - 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.
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>
I think what you want is to make your flex item (#box
) have a height and set it's overflow, not the flex container. Also, to add your 30px above and below I would remove the margin from the box and instead add padding to the container.
So, updated styles would look like this:
#wrapper {
background: grey;
height: 100%;
width: 100%;
max-height: 100%;
display: flex;
align-items: center;
justify-content: center;
padding: 30px 0; /*added*/
}
#box {
background: white;
border: 1px solid #dfdfdf;
overflow-y: auto; /*added*/
height: 100%; /*added*/
}
body,
html {
height: 100%;
width: 100%;
margin: 0;
}
* {
box-sizing: border-box;
}
#wrapper {
background: grey;
height: 100%;
width: 100%;
max-height: 100%;
display: flex;
align-items: center;
justify-content: center;
padding: 30px 0;
}
#box {
background: white;
border: 1px solid #dfdfdf;
overflow-y: auto;
height: 100%;
}
<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>