How to use safe center with flexbox?

The newer keyword safe still has bad browser support, so to get the same effect, cross browser, use auto margins for now, which should be set on the flex item.

Updated codepen

Note, to compensate for the modal‘s 50px top/bottom margin, use padding on modal-container.

.modal-container
{
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: flex-start;                /*  changed  */
  position: fixed;
  width: 100vw;
  height: 100vh;
  overflow-y: scroll;
  padding: 50px 0;                        /*  added  */
  box-sizing: border-box;                 /*  added  */
}
.modal-container > #modal
{
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: auto 0;                         /*  changed  */
  padding: 12px;
  width: 50%;
  background-color: #333;
  cursor: pointer;
}

Leave a Comment