方法一. 把圖片作為background,方法二使用img標簽。同時要有一張足夠大尺寸的圖片。
方法一. 把圖片作為background
有幾個CSS的屬性要提一下:background-size:cover,這個CSS3的屬性作用是把背景圖像擴展至足夠大,以使背景圖像完全覆蓋背景區域,背景圖像的某些部分也許無法顯示在背景定位區域中,如果不使用這個屬性,在IE11和FireFox中縮放瀏覽器,背景圖片會隨之縮小,同時使用-webkit-background-size: cover和-o-background-size: cover兼容webkit內核瀏覽器和Opera瀏覽器;background-attachment屬性設置背景圖像是否固定或者隨着頁面的其余部分滾動,當設置為fixed時頁面的其余部分滾動時,背景圖像不會移動。
div{ position:absolute; top:0; left:0; height:100%; width:100%; background-image:url("maskimg/star.jpg"); background-position: center 0; background-repeat: no-repeat; background-attachment:fixed; background-size: cover; -webkit-background-size: cover;/* 兼容Webkit內核瀏覽器如Chrome和Safari */ -o-background-size: cover;/* 兼容Opera */ zoom: 1; }
方法二.不把圖片作為背景,而是使用<img>標簽,
效果是圖片尺寸不會隨瀏覽器縮放而變化,但是如果有豎直滾動條時,圖片不會固定而會隨滾動條移動。只需要把圖片的寬度width設置成100%就行了。
<div><img id="pic" src="maskimg/star.jpg"></div> #pic{ width:100%;}
如果圖片沒有那么大,則需:
<img src="images/bodyBg.png" class="bodyBg" /> .bodyBg { position: fixed; width: 100%; height: 100%; left: 0; top: 0; z-index: -1; }