
【解決需求】
解決高度布局中部分高度固定,部分高度自適應(yīng)的問題

【實(shí)際情況中的應(yīng)用】
網(wǎng)站頂部導(dǎo)航欄(以及底部欄)固定高度,中間內(nèi)容主要區(qū)域根據(jù)屏幕大小自適應(yīng)
【解決方案】
利用絕對定位中設(shè)置位置后內(nèi)容自適應(yīng)大小確定中間高度自適應(yīng)。
1.頂部導(dǎo)航欄和底部欄設(shè)置高度固定,并利用絕對定位設(shè)置底部欄位置靠底;
2.設(shè)置中間部分為絕對定位,距離頂部和底部分別為頂部欄和底部欄的高度,剩下的部分的高度即為瀏覽區(qū)高度減去上下欄高度的差,設(shè)置寬度為100%或距離左右分別為0,則除去頂部和底部欄的區(qū)域被中間部分鋪滿;
【代碼示例】
html代碼:
<body>
<div class="header"></div>
<div class="contain">
shawnJ高度自適應(yīng)示例
</div>
<div class="foot"></div>
</body>
css代碼:
*{
padding: 0;
margin: 0;
}
.header{
width: 100%;
height: 40px;
background: #DC3E3E
}
.foot{
width: 100%;
height: 40px;
background: #222222;
position: absolute;
bottom: 0;
}
.contain{
position: absolute;
top:40px;
bottom: 40px;
left:0;
right:0;
background: #333;
color: #fff;
}
【效果截圖】

【兼容性檢測(此處只考慮chrome和IE)】
ie7+和chrome均能正常使用;
ie6中部自適應(yīng)高度失效;
【css3中的新探索】
css3中引入了calc()屬性,這個看似函數(shù)的css3屬性能計(jì)算四則運(yùn)算,可以利用其計(jì)算百分比和固定值的差值,以此來達(dá)到本文部分高度自適應(yīng)的效果,即height: calc(100% - 80px);
代碼如下所示:
html:
<body>
<div class="header"></div>
<div class="main">
ShawnJ的示例2
</div>
<div class="foot"></div>
</body>
CSS代碼如下所示:
*{
padding: 0;
margin: 0;
}
.header{
width: 100%;
height: 40px;
background: #DC3E3E;
}
.foot{
width: 100%;
height: 40px;
background: #222;
position: absolute;
bottom: 0;
}
.main{
position: absolute;
width: 100%;
height: calc(100% - 80px);
background: #333;
color:#fff;
}
兼容性:IE9+,chrome19+
效果與之前相同。
【個人思考】
目前為止為CSS常用的自適應(yīng)高度布局,可靈活應(yīng)用于多種場景。接下來是我個人對css布局中自適應(yīng)布局的一些新的嘗試,如有什么不對請大家多多指教。
解決方案探索:
利用box-sizing:border-box使得padding不影響定義的寬高;
1.給中間主體部分添加一個外層,并絕對定位覆蓋整個頁面,設(shè)置其上下內(nèi)邊距分別為頂欄和底欄的高度
2.設(shè)置中間主體部分高度為100%,則中間高度為瀏覽器高度減去上下邊欄的高度。
兼容性檢測:適用于IE6+
代碼如下:
<body>
<div class="header"></div>
<div class="wrap">
<div class="main">
ShawnJ的示例3
</div>
</div>
<div class="foot"></div>
</body>
*{
padding: 0;
margin: 0;
box-sizing: border-box;
}
.header{
width: 100%;
height: 40px;
background: #DC3E3E;
}
.wrap{
position: absolute;
top: 0;
width: 100%;
height: 100%;
padding: 40px 0;
}
.main{
width: 100%;
height: 100%;
background: #333;
}
.foot{
width: 100%;
height: 40px;
background: #222;
position: absolute;
bottom: 0;
}
以上為個人總結(jié)的高度布局方式,第一次寫簡書,當(dāng)作是自己學(xué)習(xí)前端路上的一些筆記吧。有什么不對的地方希望大家多多指正,如果有更好的方案歡迎大家指出。
希望能在評論里學(xué)到更多東西~~~
(?????)? (?????)? (?????)?