經常會碰到須要填滿整個瀏覽器,而且自適應高度的需求。首先確定會想到給容器設定height:100%,可是會沒有效果。緣由是body沒有高度,因此百分比沒法生效。css
解決方案:給html,body,標籤都加上height:100%html
<!DOCTYPE html> <html> <head> <title></title> <style type="text/css"> *{padding:0;margin: 0;} html,body,.d1{height: 100%;} .d1{background-color: red;height: 100%;} </style> </head> <body> <div class="d1"></div> </body> </html>
結果預覽css3
在此基礎上又會衍生一些變體,好比上下2行佈局,第一行固定高度,第二行自適應瀏覽器。要自適應瀏覽器高度,那麼也只能用height:100%;但有個問題,就是多出了其他部分的高度瀏覽器
優勢:簡單佈局
缺點:可能內容溢出ui
<!DOCTYPE html> <html> <head> <title></title> <style type="text/css"> *{padding:0;margin: 0;} html,body,.d1{height: 100%;} body{overflow:hidden;} .d1{background-color: red;height: 200px} .d2{height:100%;background-color:blue;} </style> </head> <body> <div class="div1"></div> <div class="div2"></div> </body> </html>
結果預覽spa
優勢:動態計算除了固定高度外的剩餘高度.net
缺點:code
兼容:absolute --- ie8+ fixed ---- ie7+xml
<!DOCTYPE html> <html> <head> <title></title> <style type="text/css"> *{padding: 0;margin: 0;} html,body{height: 100%;} .div1{height: 200px;background-color: red;position: absolute;width: 100%;top: 0;left: 0;} .div2{position: absolute;top: 200px;bottom: 0;width: 100%;}/*絕對定位 動態計算高度 ie8 及以上*/ .div3{height: 100%;float: left;width: 200px;background-color: blue;} .div4{height:100%;margin-left: 200px;background-color: yellow} </style> </head> <body> <div class="div1"> </div> <div class="div2"> <div class="div3"> </div> <div class="div4"> </div> </div> </body> </html>
優勢:完美自適應
缺點:
兼容:ie8+
<!DOCTYPE html> <html> <head> <title></title> <style type="text/css"> *{padding: 0;margin: 0;} html,body{height: 100%;} .div1{height: 200px;background-color: red;position: absolute;width: 100%;top: 0;left: 0;} .div2{height: 100%;padding-top: 200px;box-sizing:border-box;}/*脫離文檔流,改變和模型計算方式,此法用於ie8 及以上*/ .div3{height: 100%;float: left;width: 200px;background-color: blue;} .div4{height:100%;margin-left: 200px;background-color: yellow} </style> </head> <body> <div class="div1"></div> <div class="div2"> <div class="div3"> </div> <div class="div4"> </div> </div> </body> </html>
優勢:
缺點:比較麻煩,從新定義display 或者,用table佈局
兼容:ie8+
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <style type="text/css"> * { margin:0; padding:0; } html, body, #box { height:100%; font:small/1.5 "宋體", serif; } body { text-align:center; } #box { text-align:left; background:#666; display:table; width:80%; margin:0 auto; position:relative; } #box > div { display:table-row; } #header, #footer { background:#fcc; height:50px; vertical-align:bottom; } #main { background:#ccf; } #main #wrap { display:table-cell; background:#ffc; vertical-align:middle; } #text { text-align:center; } </style> </head> <body> <div id="box"> <div id="header">header</div> <div id="main"> </div> <div id="footer">footer</div> </div> </body> </html>