背景固定效果在許多的網站都能看到,今天我們一起來看一個關于CSS制作的頁面背景固定和滾動效果,應用非常的好用希望對各位帶來幫助。
如何創建一個不需要Javascript而僅僅只需CSS的background-attachment屬性就能實現頁面背景固定和滾動效果。我們看到現在有很多的網站項目使用了視差效果,通過圖片和背景的動態變化以及js腳本來產生視差,而今天我們只需要CSS即可。
HTML結構很簡單,一個class為.cd-fixed-bg的div元素用于放置固定背景圖,一個class為.cd-scrolling-bg的div元素用于滾動的部分。我們可以放置多個.cd-fixed-bg和.cd-scrolling-bg編組。
代碼如下 | 復制代碼 |
<main> <div class="cd-fixed-bg cd-bg-1"> <h1><!-- title goes here --></h1> </div> <div class="cd-scrolling-bg cd-color-2"> <div class="cd-container"> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolore incidunt suscipit similique, dolor corrupti cumque qui consectetur autem laborum fuga quas ipsam doloribus sequi... </p> </div> </div> ...多組div并列... </main> |
CSS
那么如何實現背景固定和滾動效果呢?一開始,我想使用jQuery,也許我先應該讓一個div固定位置,然后當滾動頁面時改變背景圖片,但是覺得不好弄。而簡單的我們使用幾行CSS就能做到,將要固定的元素的背景background-size值設置為cover,background-attachment的值設置為fixed,這樣就實現了單頁面的背景固定和滾動效果。請看以下代碼:
代碼如下 | 復制代碼 |
body, html, main { /* important */ height: 100%; } .cd-fixed-bg { min-height: 100%; background-size: cover; background-attachment: fixed; background-repeat: no-repeat; background-position: center center; } .cd-fixed-bg.cd-bg-1 { background-image: url("../img/cd-background-1.jpg"); } .cd-fixed-bg.cd-bg-2 { background-image: url("../img/cd-background-2.jpg"); } .cd-fixed-bg.cd-bg-3 { background-image: url("../img/cd-background-3.jpg"); } .cd-scrolling-bg { min-height: 100%; } |