Search code examples
cssmodal-dialogcss-positionstickyw3.css

CSS position: sticky behaves like fixed (within w3.css modal)


My sticky close-button for my modal doesn´t work properly. Instead of behaving sticky it behaves like a fixed element, even though I specified top:0 and -webkit-position:sticky;position:sticky; in my css rules. Below you can see my code snippet:

<html>
<head>
<style>
    .modalclose {
        position: -webkit-sticky;
        position: sticky;
        width: 100%;
        top: 0px;
    }
</style>
<link rel="stylesheet" href="./css/w3.css">
</head>
<body>
    <div class="w3-modal">
        <div class="w3-modal-content w3-display-container">
            <div style="position:absolute;top:0;left:0;height:43px;width:100%;background-color:black;"></div>
            <div onclick="javascript:void(0);" class="w3-button w3-large w3-display-topright modalclose w3-black w3-text-white">x</div>
            <div class="w3-container w3-black">
                <h1>LOREM IPSUM</h1>
            </div>
            <div class="w3-container" style="padding-bottom: 2000px">
                <h5>Lorem Ipsum</h5>
            </div>
        </div>
    </div>
</body>
</html>

In Firefox (Desktop) and Chrome (3 different mobile devices), the close-button is being treated as if it would be an fixed element, it never "sticks" to the top of the viewport (except for 1 mobile device running an older chrome version, there it works fine, but therefore the span is not click-able).
What am I doing wrong?
Here´s a link to the above code on my page: click here


Solution

  • The problem is the the .w3-modal has a fixed position and a 100px padding-top. It never leaves the screen. And it has a padding-top of 100px.

    Your .modalclose is already sticky and working fine.

    Try removing the position fixed of the .w3-modal class. If you want the modal to be fixed, then you could remove the padding-top: 100px from it, so that the .modalclose can come up to the top of the screen.