实现滚动贴合的css元素及设置
<!DOCTYPE html>
<html>
<head>
<title>实现页面滚动贴合</title>
</head>
<body>
<main>
<section>页面1</section>
<section>页面2</section>
<section>页面3</section>
<section>页面4</section>
<section>页面5</section>
</main>
</body>
</html>
css元素 :
scroll-snap-type: y mandatory;
第一个值 : 表示滚动贴合的方向
y : 纵向滚动贴合
x : 横向滚动贴合
第二个值 : 表示贴合方式
mandatory : 表示强制滚动
proximity : 当元素移动到离贴合点小于一定的距离的时候在进行贴合(注:这个距离是根据浏览器自己规定的)
**设置子元素贴合对齐方式 : **
scroll-snap-align:start
start : 下一屏的内容就会贴到main元素的顶部
end : 下一屏的内容就会贴到main元素的底部
center : 下一屏的内容就会与main元素垂直居中对齐
水平滚动贴合 案例:
<!DOCTYPE html>
<html>
<head>
<title>实现页面滚动贴合</title>
<style type="text/css">
main{
display: flex;
scroll-snap-type: x mandatory;
overflow: scroll;
height: 100vh;
width: 100vw;
}
section{
width: 100vw;
height: 100vh;
scroll-snap-align: start;
flex-shrink: 0;
}
section:nth-child(1){
text-align: center;
background-color: aqua;
color: #fff;
}
section:nth-child(2){
text-align: center;
background-color: blue;
color: #fff;
}
section:nth-child(3){
text-align: center;
background-color:blueviolet;
color: #fff;
}
</style>
</head>
<body>
<main>
<section>页面1</section>
<section>页面2</section>
<section>页面3</section>
<section>页面4</section>
<section>页面5</section>
</main>
</body>
</html>
给容器设置间距 案例:
<!DOCTYPE html>
<html>
<head>
<title>实现页面滚动贴合</title>
</head>
<body>
<main>
<h1>标题一</h1>
<section>页面1</section>
<section>页面2</section>
<section>页面3</section>
<section>页面4</section>
<section>页面5</section>
</main>
</body>
</html>
给h1的属性:
h1{
height: 80px;
position: sticky;
top: 0;
background-color: #fff;
}
若设置为贴合顶部则会有些元素会被覆盖。
可以在mian
中设置css :
scroll-padding: 80px;
大小与h1高度一致
注意 : scroll-snap-align为start时,看到另一元素的80px才能进行贴合
也可以用在ul ,li中
<main>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
</main>
ul{
scroll-snap-type: y mandatory;
}
li{
scroll-snap-align: start;
}