如何創建:視差滾動
學習如何使用 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> <!-- Container element --> <div class="parallax"></div>
上面的例子使用像素來設置圖像的高度。如果您想使用百分比,例如 100%,以使圖像適合整個屏幕,請將視差容器的高度設置為 100%。注意:您還必須將 height: 100%
應用于 <html> 和 <body>:
以百分比為單位的實例
body, html { height: 100%; } .parallax { /* 所用的圖像 */ background-image: url("img_parallax.jpg"); /* 全高 */ 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; } }
在上述代碼中,當屏幕寬度小于或等于 1366 像素時,將關閉視差滾動效果,這對于大多數平板電腦和手機都是適用的。這是通過改變 .parallax
類的 background-attachment
屬性從 fixed
到 scroll
來實現的。這樣,背景圖像就會隨著頁面的其余部分一起滾動,而不是固定在視口中。