简体   繁体   中英

Centering a div on a scrolled page

I have the following code:

<div id="overlay" style="
    display: none;
    border: solid #aa0 10px;
    width: 75vh;
    height: 80vh;
    z-index: 650;
    position: absolute;
    left:50%; top: 50%;
    transform: translate(-50%, -50%)"
>

It is hidden at first, but if I click on specific screen elements I have some jquery code that displays it with show() .

This centers perfectly if the page is not scrolled, however, if the page is scrolled when the user clicks on one of the screen elements, the overlay will appear centered as if the page was not scrolled. (ie it will be centered at the top of the page even if it is out of view).

How can I fix this so that it centers in the viewport no matter where the page is scrolled to?

you need change position from absolute to fixed

<div id="overlay" style="
    display: none;
    border: solid #aa0 10px;
    width: 75vh;
    height: 80vh;
    z-index: 650;
    position: fixed;
    left:50%; top: 50%;
    transform: translate(-50%, -50%)"
>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM