如何 - CSS 視差滾動
學習如何使用 CSS 建立“視差”滾動效果。
視差
視差滾動是一種網站趨勢,在滾動時,背景內容(例如影像)的移動速度與前景內容不同。點選下面的連結,檢視有和沒有視差滾動的網站的區別。
注意:視差滾動在移動裝置/智慧手機上並不總是有效。但是,您可以使用媒體查詢在移動裝置上關閉該效果(請參閱本頁的最後一個示例)。
如何建立視差滾動效果
使用容器元素,併為該容器新增具有特定高度的背景影像。然後使用 background-attachment: fixed
來建立實際的視差效果。其他背景屬性用於完美地居中和縮放影像。
畫素示例
<style>
.parallax {
/* 使用的影像 */
background-image: url("img_parallax.jpg");
/* 設定特定高度 */
min-height: 500px;
/* 建立視差滾動效果 */
background-attachment: fixed;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
</style>
/* 其他背景屬性用於居中和縮放影像 */
background-position: center;
自己動手試一試 »
background-repeat: no-repeat;
background-size: cover;
body, html {
height: 100%;
}
.parallax {
/* 使用的圖片 */
}
在上面的示例中,我們使用了畫素來設定影像的高度。如果您想使用百分比,例如 100%,使影像適應整個螢幕,請將視差容器的高度設定為 100%。注意:您還必須為 <html>
和 <body>
應用 height: 100%
。
height: 100%;
百分比示例
background-attachment: fixed;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
自己動手試一試 »
一些移動裝置對 background-attachment: fixed
有問題。但是,您可以使用媒體查詢來關閉移動裝置上的視差效果。
示例
/* 為所有平板電腦和手機關閉視差滾動。如果需要,請增加/減少畫素 */
@media only screen and (max-device-width: 1366px) {
.parallax {
background-attachment: scroll;
}
}
自己動手試一試 »