Can't scroll to top with modal and overlay with display flex

Viewed 1131

I have a modal with a backdrop overlay, this is my example:

https://codepen.io/tyrellrummage/full/XeRQYm/

(make the window smaller to see the top and bottom overflow).

Basically the structure is:

<div class="overlay">
    <div class="modal">
        //content
    </div>
</div>

and the current styling:

.overlay{
    display: flex;
    align-items: center;
    justify-content: center;
    overflow-y: scroll;
}

.modal{
    margin: 4rem 0;
}

this works for the bottom part of the modal, but the top part gets trimmed (cut out). How can I fix this only with CSS?

1 Answers

A very thorough explanation on why this happens can be read in this awesome answer.

Applied to your case, you need both top and bottom margins of .modal set to auto.

Which means you need to place the 4rem margins as paddings of .overlay.

Which, in turn, means you need to also apply box-sizing:border-box to it, so the paddings are subtracted from height, not added, resulting in:

.modal { 
  margin: auto 0;
}
.overlay{ 
  padding: 4rem 0;
  overflow-y:auto;
  box-sizing: border-box;
}
Related