Search code examples
htmlcssanimationkeyframe

Pure css3 slider from right side doesn't work correctly


I try write pure css and html slider for my webside. It should look like this one. It should include not only photos, but also buttons and text. So I thought about <div> (this code below shows divs behavior, when they slide from left to right and right to left). And all is beautifull when they are appearing and hiding on the left side. But the problem is when they are sliding to the right side. Then a scrollbar appear and the browser width expands.

How to fix this bug?

.mySliderContainer {
    position: relative;
    margin: 0 auto;
    width: 100%;
}

.mySliderBanner {
    position: absolute;
    display: inline-block;
    width: 100%;
    height: 100px;
}

#mySliderBannerFirst {
    background-color: tomato;
    animation: first_banner 10s ease-out infinite;
}

@keyframes first_banner {
    0% {
        right: 0px;
    }
    23% {
        right: 0px;
    }
    33% {
        right: 100%;
    }
    46% {
        right: 100%;
    }
    56% {
        right: 0px;
    }
    89% {
        right: -100%;
    }
    100% {
        right: 0px;
    }
}
<!DOCTYPE html>
<html>
    <head></head>
    <body>
        <div class="mySliderContainer">
           <div id="mySliderBannerFirst" class="mySliderBanner"></div>
        </div>
    </body>
</html>


Solution

  • This is not a bug, this is normal behavior, as when you move an element beyond the viewport, it automatically starts to scroll.

    Update your CSS like this and give it overflow: hidden (and it needs height: 100px; too) to hide the scroll bar

    .mySliderContainer {
        position: relative;
        margin: 0 auto;
        width: 100%;
        height: 100px;
        overflow: hidden;
    }
    

    Sample

    .mySliderContainer {
        position: relative;
        margin: 0 auto;
        width: 100%;
        height: 100px;
        overflow: hidden;
    }
    
    .mySliderBanner {
        position: absolute;
        display: inline-block;
        width: 100%;
        height: 100px;
    }
    
    #mySliderBannerFirst {
        background-color: tomato;
        animation: first_banner 10s ease-out infinite;
    }
    
    @keyframes first_banner {
        0% {
            right: 0px;
        }
        23% {
            right: 0px;
        }
        33% {
            right: 100%;
        }
        46% {
            right: 100%;
        }
        56% {
            right: 0px;
        }
        89% {
            right: -100%;
        }
        100% {
            right: 0px;
        }
    }
    <!DOCTYPE html>
    <html>
        <head></head>
        <body>
            <div class="mySliderContainer">
               <div id="mySliderBannerFirst" class="mySliderBanner"></div>
            </div>
        </body>
    </html>