怎麼讓Html的高度自適應屏幕高度

在寫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;
  }
};
發佈了59 篇原創文章 · 獲贊 80 · 訪問量 36萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章