在前端生涯上,常常會遇到須要容器自適應視口高度這種狀況,本文將介紹我能想到的解決這個問題的方案。
html元素的高度默認是auto(被內容自動撐開),寬度默認是100%(等於瀏覽器可視區域寬度),沒有margin和padding;javascript
body元素的高度默認是auto,寬度默認是100%,有margin而沒有padding;css
若想讓一個塊元素(如div)的高度與屏幕高度自適應,始終充滿屏幕,須要從html層開始層層添加height=100%,而又由於html,body元素的width默認就是100%,所以在裏面的div 設定width=100%時就能和屏幕等寬。html
給html、body標籤添加css屬性height=100%,而後在須要撐滿高度的容器添加css屬性height=100%,以下:前端
<html> <body> <div class="example"> </div> </body> <html>
html{ height:100%;//讓html的高度等於屏幕 } body{ height:100%; margin:0; } .example{ width: 100%; height:100%; background:rgb(55, 137, 243); }
注意:添加類名.example的元素必須是塊級元素並且須要是body的直接子元素
,也就是要設置height=100%,其父元素必須有高度java
給須要撐滿的容器添加絕對定位(absolute),而後設置top、left、right、bottom分別爲0,以下:瀏覽器
<html> <body> <div class="example"> </div> </body> <html>
.example{ position: absolute; top:0; left:0; bottom:0; right:0; background:rgb(55, 137, 243); }
注意:若目標元素的父級元素
沒有設置過相對定位(relative)或絕對定位(absolute)
,那麼目標元素將相對於html定位,html不須要設置寬高;不然相對於其設置過相對定位(relative)或絕對定位(absolute)
的父級元素
定位,且其父級元素
必須有寬度和高度,以下:佈局
<html> <body> <div class="example2"> <span class="example"></span> </div> </body> <html>
.example2{ position: relative; width:100%; height:100px; } .example{ position: absolute; top:0; left:0; bottom:0; right:0; background:rgb(55, 137, 243); }
給須要撐滿的容器添加絕對定位(absolute),而後設置top、left、right、bottom分別爲0,以下:flex
<html> <body> <div class="example"> </div> </body> <html>
.example{ position: fixed; top:0; left:0; bottom:0; right:0; background:rgb(55, 137, 243); }
注意:使用fixed後,不須要理會父級元素是否有定位屬性,均能撐滿瀏覽器可視區域,但目標元素不隨滾動容器的滾動而滾動spa
給須要撐滿的容器的父元素添加display:flex,而後給撐滿的元素添加flex:1 1 auto,以下:code
<html> <body> <div class="example"> </div> </body> <html>
html,body{ width:100%; height:100%; } body{ display: flex; } .example{ background:#fc1; flex:1 1 auto; }
注意:使用flex一樣須要父元素的有高度和寬度,不然不會撐開。
<html> <body> <div class="example"> </div> </body> <html>
<script> let example = document.getElementById('example') let height = document.documentElement.clientHeight example.style.height = `${height}px` </script>