Samir
Samir

Reputation: 79

Css scroll snap start visible element at N

Currently I am making a layout where the user can swipe left and right to access different sections on the page. I tried to find a solution, also in the official spec but with no success.

I want to achieve scroll snapping where the starting element is the second (N) div (.fridge) while allowing to swipe / snap left and right.

I prefer a CSS, but js is no problem.

What happens now is: Store (It starts here) - Fridge - Shop

What i want Store - Fridge (It starts here) - Shop Allowing me to swipe left and right

    body {
        margin: 0;
    }

    .horizontal-snap {
        display: grid;
        grid-auto-flow: column;
        width: 100vw;
        height: 100vh;
        overflow-y: auto;
        overscroll-behavior-x: contain;
        scroll-snap-type: x mandatory;
    }

    .horizontal-snap .slide {
        scroll-snap-align: center;
        width: 100vw;
        height: 100vh;
        max-width: none;
        object-fit: contain;
    }

    .shop {
        background-color: #efdefe;
    }

    .fridge {
        background-color: #a3f3d3;
    }

    .recipe {
        background-color: #0bbaa0;
    }
<div class="horizontal-snap">
    <div class="slide shop">
        <h1>shop</h1>
    </div>
    <div class="slide fridge">
        <h1>fridge</h1>
    </div>
    <div class="slide recipe">
        <h1>Recipe</h1>
    </div>
</div>

Upvotes: 0

Views: 1458

Answers (1)

Tatul Mkrtchyan
Tatul Mkrtchyan

Reputation: 371

You need to use a Javascript

const element = document.getElementsByClassName('fridge')[0];
document.getElementsByClassName('horizontal-snap')[0].scrollLeft = element.offsetLeft;
body {
            margin: 0;
        }

        .horizontal-snap {
            display: grid;
            grid-auto-flow: column;
            width: 100vw;
            height: 100vh;
            overflow-y: auto;
            overscroll-behavior-x: contain;
            scroll-snap-type: x mandatory;
        }

        .horizontal-snap .slide {
            scroll-snap-align: center;
            width: 100vw;
            height: 100vh;
            max-width: none;
            object-fit: contain;
        }

        .shop {
            background-color: #efdefe;
        }

        .fridge {
            background-color: #a3f3d3;
        }

        .recipe {
            background-color: #0bbaa0;
        }
<div class="horizontal-snap">
    <div class="slide shop">
        <h1>shop</h1>
    </div>
    <div class="slide fridge">
        <h1>fridge</h1>
    </div>
    <div class="slide recipe">
        <h1>Recipe</h1>
    </div>
</div>

Upvotes: 1

Related Questions