怎麼讓Html的高度自適應螢幕高度
阿新 • • 發佈:2018-12-23
在寫css靜態頁面的時候讓Html的高度自適應螢幕高度是一個常見的需求,比如你有一個需要置底的bottom按鈕,需要在內容不足一屏的時候顯示在螢幕的底部,在內容超過一屏的時候顯示在所有內容的底部。
效果圖:
CSS的做法
html {
height: 100%;
display: table;
}
body {
display: table-cell;
height: 100%;
}
又學了一種新方法,使用flex佈局:
<div class="container">
<header></header>
<content ></content>
<footer></footer>
</div>
.container {
display: flex;
min-height: 100vh;
flex-direction: column;
}
header {
background: #cecece;
min-height: 100px;
}
content {
background: #bbbbbb;
flex: 1; /* 1 代表盡可能最大,會自動填滿除了 header footer 以外的空間 */
}
footer {
background : #333333;
min-height: 100px;
}
JS的做法
css的做法有時候會在定位的時候造成一些麻煩,可以嘗試使用js去動態改變html的高度
基於zepto
$(document).ready(function(){
var windowHeight = $(window).height();
if($(this).height() < windowHeight){
$(this).height(windowHeight);
}
});
原生js
window.onload = function(){
var winHeight = 0 ;
if (window.innerHeight){
winHeight = window.innerHeight;
}else if ((document.body) && (document.body.clientHeight)){
winHeight = document.body.clientHeight;
}
var html = document.getElementsByTagName('html')[0];
if(document.body.offsetHeight < windowHeight){
html.style.height = windowHeight;
}
};