設置HTML頁面最小高度為窗口高度的方法
先看html和效果圖
<!DOCTYPE html>
<html>
<head>
<style>
body,p{
margin:0;
}
.header,.footer{
background:#000;
height:60px;
}
/*兼容ie8
html,body{
height:100%;
}
*/
.auto-height{
/*兼容ie8
min-height:100%;
*/
min-height:100vh;
margin-top:-60px;
margin-bottom:-60px;
/*設置內邊距方式一*/
box-sizing:border-box;
padding-top:60px;
padding-bottom:60px;
}
/*設置內邊距方式二
.auto-height>div{
padding-top:60px;
padding-botom:60px;
}
*/
</style>
</head>
<body>
<div class="header">
</div>
<div class="main auto-height" id="main-con">
<div>
<p>設置頁面最小高度為窗口高度的方法</p>
</div>
</div>
<div class="footer">
</div>
<!-- script>
var mainElem=document.getElementById("main-con");
document.onreadystatechange=function(){
if(document.readyState=="complete"){
mainElem.style.minHeight=(document.documentElement.clientHeight-120)+"px";
window.onresize=function(){
mainElem.style.minHeight=(document.documentElement.clientHeight-120)+"px";
};
}
};
</script -->
</body>
</html> 效果圖:

這里有兩種方法:
第一種是使用css實現:
1. 給main元素添加樣式:
min-height:100vh; margin-top:-60px;//數值等于頁面頭部高度 margin-bottom:-60px;//數值等于頁面尾部高度
margin的高度是頁面頭部和尾部的高度。
2. 為了讓main元素里的所有內容都顯示出來,要增加相應的內邊距,這里有兩種方法:
box-sizing:border-box;//將main元素的寬高計算方式更改為包含內邊距和邊框 padding-top:60px;//數值等于頁面頭部高度 padding-botom:60px;//數值等于頁面尾部高度
或設置其子元素的內邊距:
.auto-height>div{
padding-top:60px;//數值等于頁面頭部高度
padding-botom:60px;//數值等于頁面尾部高度
} 3.由于ie8不支持vh單位,所以如果需要兼容ie8的話,可以將html和body的高度都設為100%,再設置main元素的最小高度為100%(min-height:100%),其他的設置不變。
html,body{
height:100%;
} 第二種是使用JavaScript來實現:
使用JavaScript來動態設置main元素的最小高度即可,這里提供其中一種實現方式
var mainElem=document.getElementById("main-con");//獲得main元素
document.onreadystatechange=function(){
if(document.readyState=="complete"){//頁面加載完成時執行
mainElem.style.minHeight=(document.documentElement.clientHeight-120)+"px";//初始化最小高度
window.onresize=function(){//窗口大小改變時改變main元素的最小高度
mainElem.style.minHeight=(document.documentElement.clientHeight-120)+"px";
};
}
}; 最小高度的值=窗口的高度-頁面頭部高度-頁面尾部高度。
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!