【解決需求】
解決高度布局中部分高度固定,部分高度自適應的問題
【實際情況中的應用】
網站頂部導航欄(以及底部欄)固定高度,中間內容主要區域根據屏幕大小自適應
【解決方案】
利用絕對定位中設置位置后內容自適應大小確定中間高度自適應。
1.頂部導航欄和底部欄設置高度固定,并利用絕對定位設置底部欄位置靠底;
2.設置中間部分為絕對定位,距離頂部和底部分別為頂部欄和底部欄的高度,剩下的部分的高度即為瀏覽區高度減去上下欄高度的差,設置寬度為100%或距離左右分別為0,則除去頂部和底部欄的區域被中間部分鋪滿;
【代碼示例】
html代碼:
<body>
<div class="header"></div>
<div class="contain">
shawnJ高度自適應示例
</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中部自適應高度失效;
【css3中的新探索】
css3中引入了calc()屬性,這個看似函數的css3屬性能計算四則運算,可以利用其計算百分比和固定值的差值,以此來達到本文部分高度自適應的效果,即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常用的自適應高度布局,可靈活應用于多種場景。接下來是我個人對css布局中自適應布局的一些新的嘗試,如有什么不對請大家多多指教。
解決方案探索:
利用box-sizing:border-box使得padding不影響定義的寬高;
1.給中間主體部分添加一個外層,并絕對定位覆蓋整個頁面,設置其上下內邊距分別為頂欄和底欄的高度
2.設置中間主體部分高度為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;
}
以上為個人總結的高度布局方式,第一次寫簡書,當作是自己學習前端路上的一些筆記吧。有什么不對的地方希望大家多多指正,如果有更好的方案歡迎大家指出。
希望能在評論里學到更多東西~~~
(?????)? (?????)? (?????)?