如何在 CSS 中建立視差滾動效果?
透過給不同的背景和前景內容規定不同的速度,我們可以使用 CSS 建立視差滾動效果。當向上或向下滾動時,你可以輕鬆地注意到這一點,通常你可以在網站的首頁上找到這樣的效果。
設定影像
首先,使用 background-image 屬性放置和影像。使用 url,為背景影像指定連結 −
background-image: url("https://tutorialspoint.tw/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.tw/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>
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP