htmlcssscroll-snap-type

scroll-snap-type doesn't work, How can I fix it?


It is scrolled down as it originally works, I mean, like there's no scroll-snap option. why?

html code below:

<body>
    <noscript>~~</noscript>
    <div id="background"></div>
    <header>
        <nav><a href="/"><img src="~~" alt="To Mainpage"></a></nav>
        <nav>
            <ul>
                <li><a href="/">~~</a></li>
                <li><a href="/">~~</a></li>
            </ul>
        </nav>
    </header>
    <main>
        <div id="container">
            <section id="first">
                <h1>~~</h1>
                <article>~~</article>
            </section>
            <section id="second"></section>
        </div>
    </main>
</body>

and CSS code below:

#container {
    scroll-snap-type: y mandatory;
    overflow-y: scroll;
}

#container > section {
    height: 100vh;
    scroll-snap-align: start;
}

Solution

  • Make sure to give your parent container a height value, as shown in the example below.

    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    #container {
        display: flex;
        overflow: auto;
        outline: 1px dashed lightgray;
        flex: none;
        width: 100%;
        height: 100vh;
        flex-flow: column nowrap;
        scroll-snap-type: y mandatory;
    }
    
    #container > section {
        width: 100%;
        height: 100%;
        scroll-snap-align: start;
        flex: none;
    }
    
    #first, #third {
      background: #ccc;
    }
    
    #second, #fourth {
      background: red;
    }
    <div id="container">
      <section id="first"></section>
      <section id="second"></section>
      <section id="third"></section>
      <section id="fourth"></section>
    </div>