1

I'm using some flex box attributes to place a simple div to the center of the screen :

//CSS

html {
    width: 100%;
    height: 100%;
}

body {
    width: 100%;
    height: 100%;
    margin: 0px;
    display: flex;
    align-items: center;
    justify-content: center;
}

div {
    height: 500px;
    width: 500px;
    background-color: red;
    border: 5px solid black;
}

//HTML

<div></div>

It's working perfect but when I reduce the height of my screen to a size smaller than my div (smaller than 500px), I end up with a weird truncation : I can scroll down and see the bottom border but for some reason when I scroll up I can't reach the top border, it's hidden.

Am I missing something ? Anyone knows how to fix this ? I created a codepen to demonstrate the issue : https://codepen.io/stepinsight/full/MqmEME

Thanks heaps for your help !

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
sphax
  • 55
  • 1
  • 7

1 Answers1

3

Instead align-items:center; you can use margin:auto on the flex child to center it :

html {
 width: 100%;
 height: 100%;
}

body {
 width: 100%;
 height: 100%;
 margin: 0px;
 display: flex; 
 justify-content: center;
}

div {
 height: 500px;
 width: 500px;
 background-color: red;
 border: 5px solid black;
 margin:auto;
}
<div></div>

fork of your pen Note: justify-content is also removed on the codepen, when margin:auto; for a flex child works for both axis. flex-shrink:0; is also added so the container do not horizontaly shrinks (and also hides the left border) while the screeen becomes smaller in its width too.

G-Cyrillus
  • 101,410
  • 14
  • 105
  • 129
  • Thanks for your help, it works perfect ! Can't believe I didn't know about the margin:auto working for both axes :D You made my day ! – sphax Sep 03 '18 at 21:26