【问题标题】:CSS scroll snap is not working with CSS GridCSS 滚动捕捉不适用于 CSS Grid
【发布时间】:2019-08-29 10:44:48
【问题描述】:

在 Flexbox 中使用 CSS 滚动捕捉时,捕捉效果很好:

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
.slider {
  font-family: sans-serif;
  scroll-snap-type: mandatory;
  scroll-snap-points-y: repeat(100vw);
  scroll-snap-type: x mandatory;
  display: flex;
  overflow-x: scroll;
}
section {
  border-right: 1px solid white;
  padding: 1rem;
  min-width: 100vw;
  height: 100vh;
  scroll-snap-align: start;
  text-align: center;
  position: relative;
}
h1 {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  text-align: center;
  color: red;
  width: 100%;
  left: 0;
  font-size: calc(1rem + 3vw);
}
<div class="slider">
  <section>
    <h1>Section One</h1>
  </section>
  <section>
    <h1>Section Two</h1>
  </section>
  <section>
    <h1>Section Three</h1>
  </section>
  <section>
    <h1>Section Four</h1>
  </section>
  <section>
    <h1>Section Five</h1>
  </section>
</div>

但是,当尝试将 CSS Grid 与 CSS Snap 一起使用时,它似乎不起作用:

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
.slider {
  font-family: sans-serif;
  scroll-snap-type: mandatory;
  scroll-snap-points-y: repeat(100vw);
  scroll-snap-type: x mandatory;
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(auto-fill, 100vw);
  overflow-x: scroll;
  width: 600vw;
}
section {
  border-right: 1px solid white;
  padding: 1rem;
  min-width: 100vw;
  height: 100vh;
  scroll-snap-align: start;
  text-align: center;
  position: relative;
}
h1 {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  text-align: center;
  color: red;
  width: 100%;
  left: 0;
  font-size: calc(1rem + 3vw);
}
<div class="slider">
  <section>
    <h1>Section One</h1>
  </section>
  <section>
    <h1>Section Two</h1>
  </section>
  <section>
    <h1>Section Three</h1>
  </section>
  <section>
    <h1>Section Four</h1>
  </section>
  <section>
    <h1>Section Five</h1>
  </section>
</div>

这种行为的原因是什么?有没有办法让 CSS Grid 与 CSS Snap 一起工作?

【问题讨论】:

标签: html css css-grid


【解决方案1】:

- 这种行为的原因是什么?

第一个问题没有答案。

- 有没有办法让 CSS Grid 与 CSS Snap 一起工作?

是的,Max Kohler(在 CSS Scroll Snapping tutorial 中)创建了一个带有捕捉的 CSS 网格,但是他需要使用一个名为 css-scroll-snap-polyfill 的 JS 独立脚本来进行捕捉上班。

他创建的 Codepen 演示链接:https://codepen.io/maxakohler/pen/MBWJKm

要使用他的方法,你需要将这个 JS 脚本添加到你的网站:

<script src="https://bundle.run/css-scroll-snap-polyfill@0.1.2"></script>

然后在加载DOM时调用这个JS函数:

cssScrollSnapPolyfill()

它应该像他的 Codepen 演示那样工作。

【讨论】:

    猜你喜欢
    • 2019-07-14
    • 2019-11-08
    • 2020-01-11
    • 1970-01-01
    • 2019-07-07
    • 2017-12-25
    • 2020-08-26
    • 2020-08-07
    • 2022-09-23
    相关资源
    最近更新 更多