3

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?

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
nick
  • 2,819
  • 5
  • 33
  • 69
  • You need to add `.overlay{ padding: 4rem 0;overflow-y:auto;box-sizing: border-box;} .modal{ margin: auto 0;}` to your CSS to apply Michael_B's solution ([pen here](https://codepen.io/anon/pen/aLWeKZ).). Another option is to check if `.modal`'s height is smaller than `.overlay`'s and adjust the `align-items` property: `if(document.querySelector('.overlay').clientHeight < document.querySelector('.overlay > .modal').clientHeight){document.querySelector('.overlay').style = 'align-items: flex-start;';}` @Michael_B: it's not an ***exact*** duplicate. Cheers! – tao Sep 28 '17 at 22:35
  • Thanks actually I used `align-items: flex-start` and it worked. If you want, answer it and I'll mark as correct. – nick Sep 28 '17 at 22:59
  • Duplicate questions can't be answered. But it's ok, don't worry. Michael is, in principle, right. Your question ***is*** a duplicate. The reason I said it is not an **exact** duplicate is because you also need to know to apply `box-sizing:border-box` to `.overflow`, which requires a decent level of CSS knowledge. In terms of being helpful to future visitors, your question is on the edge between being a duplicate and deserving its own, proper, answer. It's debatable. – tao Sep 28 '17 at 23:03
  • @AndreiGheorghiu, go ahead and post a proper answer. Thanks for the feedback. – Michael Benjamin Sep 28 '17 at 23:14
  • 1
    Related: https://stackoverflow.com/q/33454533/3597276 – Michael Benjamin Sep 28 '17 at 23:15

1 Answers1

3

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;
}
tao
  • 82,996
  • 16
  • 114
  • 150
  • Nice! btw, adding padding 4rem 0 to the container works but now the bottom is cut out – nick Sep 29 '17 at 00:41