Lemme set the stage a bit here.
You have a website and, like most, it scrolls.
This website will have modals. You’ll probably
position: fixed the modal so that it’s predictably positioned regardless of scrolling. It’s possible the modal itself will scroll.
Notice the modal has a close button. We can
position: absolute that in the upper-right corner, but if our modal scrolls, it’s a problem.
Should be a job for more
position: fixed, right? Not really, sadly, as there is no such thing as a local context for
Well… actually there kinda (weirdly) is. If the modal has any sort of CSS transform on it (and it might already if you center it using the ol’
left: 50%; transform: translateX(-50%); trick) then the fixed position close button will come back home:
But… as the transform helped pull the close button back into place, you can see it behaves like
position: absolute and not
position: fixed. ¯\_(ツ)_/¯
There is a possibility here, though. The idea is that
position: sticky is, in a sense, a locally scoped
position: fixed. If we position the close button at the
top: 0 anyway, it’ll just stick there as the modal scrolls down.
I just thought this was an interesting possibility. Ultimately, to be honest, if I had modals I worried about scrolling, I’d probably have like a
.modal-header container and a
.modal-content container. The header would sit on top always and the container would be the thing that could scroll.
Quick and dirty codepen example here https://codepen.io/ashconnolly/pen/wmrNJK
That’s a really interesting solution to this issue. I actually noticed it bugging me a bit on the CodePen assets panel from time to time, and wanted to mention it, but I realized I had no solutions to even offer. That would be a cool change to add!
What about ditching the close button entirely?
One could place a “fake” close button on the top right side of the overlay element, but eventually, If clicking outside the modal (on the overlay element) will close it, why bother with a close button at all? Perhaps for accessibility?
Thanks that will be useful. :)
I have previously played around with using auto positions to get the same effect but it’s pretty buggy in IE11 and Edge.
The position:sticky solution looks a much neater way to do this.