当将 CSS 滚动捕捉与 Flexbox 结合使用时,捕捉效果很好:
* {
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);
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)
然而,当尝试将 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);
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)
这种行为的原因是什么?有没有办法让 CSS Grid 与 CSS Snap 一起工作?
- 这种行为的原因是什么?
第一个问题没有答案。
- 有没有办法让 CSS Grid 与 CSS Snap 一起工作?
是的,Max Kohler(在CSS 滚动对齐教程中)创建了一个带有对齐功能的 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>
Run Code Online (Sandbox Code Playgroud)
然后当 DOM 加载时调用这个 JS 函数:
cssScrollSnapPolyfill()
Run Code Online (Sandbox Code Playgroud)
它应该像他的 Codepen 演示一样工作。