Home > Back-end >  How to stop modal from scrolling up when closing it?
How to stop modal from scrolling up when closing it?

Time:02-18

I'm trying to make a modal using pure CSS and HTML. So far I have this

    [id^=modal] {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
    }
    [id^=modal]:target {
        display: block;
    }
    input[type=checkbox] {
        position: absolute;
        clip: rect(0 0 0 0);
    }
    .popup {
        width: 100%;
        height: 100%;
        z-index: 99999;
    }
    .popup__overlay {
        position: fixed;
        z-index: 1;
        display: block;
        top: 0;
        left: 0;
        height: 100%;
        width: 100%;
        background: #000000b3;
    }
    .popup__wrapper {
        position: fixed;
        z-index: 9;
        width: 80%;
        max-width: 1200px;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        border-radius: 8px;
        padding: 58px 32px 32px 32px;
        background: #fff;
    }
    .popup__close {
        position: absolute;
        top: 16px;
        right: 26px;
    }
   
   
   <a href="#modal1">Open modal 1</a>
    
    <div  id="modal1">
        <a  href="#"></a>
        <div >
            <a  href="#">Close icon here</a>
            <p>POPUP 1 : CONTENT HERE</p>
        </div>
    </div>

The problem now is when I'm closing this modal, it's scrolling up. I think this is due to href="#". Is there any other way to close this modal using CSS that would not make it scroll up? If it's not possible, how can I do it with as little javascript as possibe?

CodePudding user response:

Instead of href = "#" use href = "#!". Your example is below:

[id^=modal] {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
    }
    [id^=modal]:target {
        display: block;
    }
    input[type=checkbox] {
        position: absolute;
        clip: rect(0 0 0 0);
    }
    .popup {
        width: 100%;
        height: 100%;
        z-index: 99999;
    }
    .popup__overlay {
        position: fixed;
        z-index: 1;
        display: block;
        top: 0;
        left: 0;
        height: 100%;
        width: 100%;
        background: #000000b3;
    }
    .popup__wrapper {
        position: fixed;
        z-index: 9;
        width: 80%;
        max-width: 1200px;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        border-radius: 8px;
        padding: 58px 32px 32px 32px;
        background: #fff;
    }
    .popup__close {
        position: absolute;
        top: 16px;
        right: 26px;
    }
<a href="#modal1">Open modal 1</a>
    
    <div  id="modal1">
        <a  href="#!"></a>
        <div >
            <a  href="#!">Close icon here</a>
            <p>POPUP 1 : CONTENT HERE</p>
        </div>
    </div>

  • Related