1、添加背景圖
HTML代碼:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/> <meta name="format-detection" content="telephone=no"/> <meta name="format-detection" content="email=no"/> <title></title> <style> *{margin:0; padding:0;} #wrap{ width:100%; height:auto; background:url('images/page.jpg') no-repeat center center; background-size:cover; } </style> </head> <body> <div id="wrap"> </div> </body> </html>
我們可以看看頁面效果截圖:
為了達到適應不同終端的屏幕大小,我們又不能把寬高寫死,那怎么辦呢?可以采取以下方法:
HTML代碼:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/> <meta name="format-detection" content="telephone=no"/> <meta name="format-detection" content="email=no"/> <title></title> <style> *{margin:0; padding:0;} #wrap{ width:100%; height:100%; background:url('images/page-small.jpg') no-repeat; background-size:cover; position:fixed; z-index:-10; background-position:0 0; } </style> </head> <body> <div id="wrap"> </div> </body> </html>
再來看看頁面效果:
手機頁面效果
注意:如果去掉div,直接把樣式加在body上面的話,在PC端瀏覽器可以顯示,安卓手機里面也可以顯示,但是在蘋果手機里面就無法顯示。多次反復測試,均重現此bug(如有朋友遇到此類問題的正解,歡迎指教!)
(上圖為蘋果機型下的截圖)
2、通過img標簽添加背景圖
HTML代碼:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/> <meta name="format-detection" content="telephone=no"/> <meta name="format-detection" content="email=no"/> <title></title> <style> *{margin:0; padding:0;} </style> </head> <body> <div id="wrap"> <img class="imgBcground" src="images/page-small.jpg" alt=""> </div> </body> </html>
查看頁面效果時發現,圖片是以百分百實際大小呈現,顯然不是我們想要的效果
跟上面的例子很相像,我們只需要稍加修改就好
HTML代碼:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/> <meta name="format-detection" content="telephone=no"/> <meta name="format-detection" content="email=no"/> <title></title> <style> *{margin:0; padding:0;} .imgBcground{ display:block; width:100%; height:100%; position:fixed; z-index:-10; } </style> </head> <body> <div id="wrap"> <img class="imgBcground" src="images/page-small.jpg" alt=""> </div> </body> </html>
在不同模擬機型下查看頁面效果均可以實現:
關于background-size屬性,W3C是這么定義的
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com