如何在 CSS 中创建视差滚动效果?


通过给不同的背景和前景内容规定不同的速度,我们可以使用 CSS 创建视差滚动效果。当向上或向下滚动时,你可以轻松地注意到这一点,通常你可以在网站的首页上找到这样的效果。

设置图像

首先,使用 background-image 属性放置和图像。使用 url,为背景图像指定链接 −

background-image: url("https://tutorialspoint.com/static/images/home/coding-groundhero.svg");

设置高度

你需使用 min-height 属性设置最小高度 −

min-height: 500px;

创建视差滚动效果

视差滚动效果可以使用 background-attachment 属性设置。此处将 fixed 值设置 −

background-attachment: fixed;
background-position: center;
background-repeat: no-repeat;
background-size: cover;

为内容设置高度

让内容以 div 形式设置,这些内容可在使用视差滚动效果时在滚动中显示。高度使用 height 属性设置 −

.dist {
   height:1000px;
   background-color: rgba(102,234,99,0.5);
}

示例

以下示例将显示 CSS 视差滚动效果 −

<!DOCTYPE html>
<html>
<head>
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <style>
      .scrollEffect {
         background-image: url("https://tutorialspoint.com/static/images/home/coding-groundhero.svg");
         min-height: 500px; 
         background-attachment: fixed;
         background-position: center;
         background-repeat: no-repeat;
         background-size: cover;
      }
      .dist {
         height:1000px;
         background-color: rgba(102,234,99,0.5);
      }
   </style>
</head>
<body>
   <p>The parallax scrolling effect can be seen when a user scrolls the web page up and down.</p>
   <div class="scrollEffect"></div>
   <div class="dist">
      Sed a porttitor enim. Integer euismod dui massa, at posuere sem fermentum at. Fusce vehicula fringilla tortor, ut mattis sapien tristique ac. Phasellus eleifend malesuada orci, et facilisis arcu egestas vel. Duis in tempus libero. Nunc nibh arcu, tempus quis lectus ut, blandit tincidunt felis. Suspendisse potenti.
   </div>
</body>
</html>

更新日期:2023-12-08

208 次浏览

开启您的职业生涯

完成课程以获得认证

入门
广告
© . All rights reserved.