web容器如何自适应视口大小

前言

在前端生涯上,常常会遇到须要容器自适应视口高度这种状况,本文将介绍我能想到的解决这个问题的方案。

基础知识

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)

给须要撑满的容器添加绝对定位(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);
    }

方法三:使用固定定位(fixed)

给须要撑满的容器添加绝对定位(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

方法四:使用flex布局

给须要撑满的容器的父元素添加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一样须要父元素的有高度和宽度,不然不会撑开。

方法五:使用javascript获取浏览器高度

<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>
相关文章
相关标签/搜索