【问题标题】:What are the bare necessities for CSS snap scroll to work?CSS snap scroll 工作的基本必需品是什么?
【发布时间】:2019-04-15 11:21:06
【问题描述】:

我一直在尝试实现一个超级简单的水平快照滚动(如下所示:https://css-tricks.com/practical-css-scroll-snapping),但我一直失败。我可能已经在这里搜索了所有问题和答案,但没有任何帮助。

我的代码很简单,我只在父级上声明scroll-snap-type: y mandatory;,在子级上声明scroll-snap-align: center;。而且我很确定这不是浏览器问题(因为我已经用许多不同的浏览器尝试过)。我在这里想念什么?或者我不明白什么?

这是我的(不工作的)CodePen:https://codepen.io/anon/pen/XyNNGY

html:

<div class='parent'>
  <div class='child'>Section 1</div>
  <div class='child two'>Section 2</div>
  <div class='child'>Section 3</div>
</div>

css:

  body {
    margin: 0;
  }

  .parent {
    scroll-snap-type: y mandatory;
  }

  .child {
    scroll-snap-align: center;
    width: 100vw;
    height: 100vh;
    background-color: pink;
  }

  .two {
    background-color: crimson;
  }

已经感谢了一百万。

【问题讨论】:

    标签: html css scroll-snap-points


    【解决方案1】:

    您指定为滚动捕捉容器的元素必须是滚动条所附加到的元素。在您的情况下,父元素没有滚动条 - 滚动条属于视口,并且父元素超出了视口的大小而没有生成自己的滚动条。因此,scroll-snap-type 属性应应用于body(或html),而不是父级:

    body {
      margin: 0;
      scroll-snap-type: y mandatory;
    }
    
    .child {
      scroll-snap-align: center;
      width: 100vw;
      height: 100vh;
      background-color: pink;
    }
    
    .two {
      background-color: crimson;
    }
    <div class='parent'>
      <div class='child'>Section 1</div>
      <div class='child two'>Section 2</div>
      <div class='child'>Section 3</div>
    </div>

    【讨论】:

    • 感谢您的精彩解释!这真的很有帮助。
    【解决方案2】:

    这样试试吧。

    body {
      margin: 0;
    }
    
    .parent {
      max-height: 100vh;
      overflow-y: scroll;
      scroll-snap-type: y mandatory;
    }
    
    .child {
      scroll-snap-align: center;
      height: 100vh;
      background-color: pink;
    }
    
    .child:nth-child(even) {
      background-color: crimson;
    }
    <div class='parent'>
      <div class='child'>Section 1</div>
      <div class='child'>Section 2</div>
      <div class='child'>Section 3</div>
    </div>

    【讨论】:

    • 非常感谢!我已经接受了@BoltClock 的回答,因为它帮助我更好地理解了滚动捕捉的工作原理,但你的回答也非常有助于提醒你可以通过设置最大高度来使父级可滚动(因此可滚动) .非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-25
    • 1970-01-01
    • 2021-05-26
    • 2019-10-14
    • 2020-01-26
    相关资源
    最近更新 更多