<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>自適應布局</title> <style type="text/css"> body{ margin: 0; } .absolute_father{ width: 400px; height: 300px; background-color: #cfcfcf; position: relative; } .absolute_son{ width: 60%; height: 20%; margin-left: 10%; margin-top: 10%; padding:10%; position: absolute; top: 10%; left:10%; } .float_father{ width: 400px; height: 300px; background-color: #cfcfcf; overflow: hidden; } .float_son{ width: 20%; height: 20%; margin-left: 10%; margin-top: 10%; } .static_father{ width: 100%; height: 40%; background-color: #cfcfcf; } .static_son{ width: 50%; height: 20%; } .div_block{ margin-top: 100px; } .text_block{ } </style> </head> <body> <div> 移動端網頁的自適應布局。 這樣可以使屏幕大小不一的手機展示的頁面布局比例一致。 我們先不用css3的box-flex屬性,而是用百分比設置。 </div> <div class="div_block"> <div>絕對定位的參考標准</div> <div class="absolute_father"> <div class="absolute_son"> 我是絕對定位塊,可以看到子元素的left是參照父元素的寬W,top是參照父元素的高H。子元素的寬參照W,高參照父元素的H。子元素的margin-left參照W,<span style="color:red;">margin-top也是參照W</span>。這是因為margin:10px 10px 10px 10px;,可以縮寫成一個margin:10px,為了數值的統一,也就只參考了父元素的W。padding是一樣的道理。 </div> </div> </div> <div class="div_block"> <div>float元素的參考標准</div> <div class="float_father"> <div class="float_son">我是float塊,子元素的寬參照W,高參照父元素的H</div> </div> </div> <div class="div_block"> <div>static元素的參考標准</div> <div class="static_father"> <div class="static_son">我是static塊,子元素的寬參照W,高參照父元素的H。如果父元素的父height是auto,那么父元素的height就是靠content撐起,子元素設置height的百分比無效。</div> </div> </div> <div class="div_block"> <div>自適應圖片的定高</div> <div> 有時候,某個區塊的高度是靠內容撐起,並沒有設置高度。那么如何統一設置圖片的高度呢?解決思路是,用定寬高比的透明圖來撐起高度。因為只對圖片設置寬度,高度會按照寬高比進行定高。 </div> </div> <div class="div_block"> <div>文字自適應大小</div> <div class="text_block"> 請看demo2 </div> </div> </body> </html>
demo2
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0" name="viewport" /> <title>文字自適應</title> <style type="text/css"> body{ margin: 0; font-size: 62.5%; } .page{ width: 100%; font-size: 1.3em; } </style> </head> <body> <div class="page">我們拿到手的移動端網頁的設計稿通常是640px寬,文字大小也通常是26px。而你實際寫的網頁是320px寬,文字13px大小。div和圖片的寬高,可以通過設計稿的百分比得出,而文字</div> <script type="text/javascript"> function $(str) { return document.querySelectorAll(str); } var body_width = window.innerWidth; var rate = body_width / 320; $(".page")[0].style.fontSize = rate*(1.3) + "em"; console.log(body_width); console.log(rate); console.log($(".page")[0]); </script> </body> </html>