HTML5----響應式(自適應)網頁設計
第一步:在網頁代碼的頭部,加入一行viewport元標簽
[html] view plain copy
- <meta name="viewport" content="width=device-width, initial-scale=1" />
viewport是網頁默認的寬度和高度,
上麵這行代碼的意思是:網頁寬度默認等於屏幕寬度(width=device-width),
原始縮放比例(initial-scale=1)為1.0,即網頁初始大小占屏幕麵積的100%。
所有主流瀏覽器都支持這個設置,包括IE9。對於那些老式瀏覽器(主要是IE6、7、8),需要使用css3-mediaqueries.js
[javascript] view plain copy
- <!--[if lt IE 9]>
- <script src="https://css3-mediaqueries-js.googlecode.com/svn/trunk/css3-mediaqueries.js"></script>
- <![endif]-->
[html] view plain copy
- width:auto; / width:XX%;
第三步:(注意)字體大小
字體大小是頁麵默認大小的100%,即16像素
字體不要使用絕對大小"PX",要使用相對大小“REM”
[html] view plain copy
- html{font-size:62.5%;}
[html] view plain copy
- body {font:normal 100% Arial,sans-serif;font-size:14px; font-size:1.4rem; }
第四步:流動布局
"流動布局"的含義是,各個區塊的位置都是浮動的,不是固定不變的
[html] view plain copy
- .left{ width:30%; float:left}
- .right{ width:70%; float:right;}
第五步:選擇加載CSS
"自適應網頁設計"的核心,就是CSS3引入的Media Query模塊。自動探測屏幕寬度,然後加載相應的CSS文件
[html] view plain copy
- <link rel="stylesheet" type="text/css" media="screen and (max-device-width: 600px)"
- href="style/css/css600.css" />
如果屏幕寬度在600像素到980像素之間,則加載css600-980.css文件
[html] view plain copy
- <link rel="stylesheet" type="text/css" media="screen and (min-width: 600px) and (max-device-width: 980px)"
- href="css600-980.css" />
另有(不建議使用):除了用html標簽加載CSS文件,還可以在現有CSS文件中加載
[html] view plain copy
- @import url("css600.css") screen and (max-device-width: 600px);
[html] view plain copy
- @media screen and (max-device-width: 400px) { .left{ float:none;} }
第七步:圖片的自適應
"自適應網頁設計"還必須實現圖片的自動縮放。
[html] view plain copy
- img, object {max-width: 100%;}
老版本的IE不支持max-width,所以隻好寫成:
[html] view plain copy
- img {width: 100%;}
windows平台縮放圖片時,可能出現圖像失真現象。這時,可以嚐試使用IE的專有命令
[html] view plain copy
- img { width:100%; -ms-interpolation-mode: bicubic;}
或使用js--imgSizer.js
[javascript] view plain copy
- addLoadEvent(function() {
- var imgs = document.getElementById("content").getElementsByTagName("img");
- imgSizer.collate(imgs);
- });
注:如有條件的話,最好還是根據不同大小的屏幕,加載不同分辨率的圖片
簡易式操作:
[html] view plain copy
- <style type="text/css">
- img{ max-width:100%;}
- video{ max-width:100%; height:auto;}
- header ul li{ float:left; list-style:none; list-style-type:none; margin-right:10px;}
- header select{display:none;}
- @media (max-width:960px){
- header ul{ display:none;}
- header select{ display:inline-block;}
- }
- </style>
- <body>
- <header>
- <ul>
- <li><a href="#" class="active">Home</a></li>
- <li><a href="#">AAA</a></li>
- <li><a href="#">BBB</a></li>
- <li><a href="#">CCC</a></li>
- <li><a href="#">DDD</a></li>
- </ul>
- <select>
- <option class="selected"><a href="#">Home</a></option>
- <option value="/AAA">AAA</option>
- <option value="/BBB">BBB</option>
- <option value="/CCC">CCC</option>
- <option value="/DDD">DDD</option>
- </select>
- </header>
- </body>
最後更新:2017-11-18 09:34:14