前言
在前端生涯上,经常会遇到需要容器自适应视口高度这种情况,本文将介绍我能想到的解决这个问题的方案。
基础知识
html元素的高度默认是auto(被内容自动撑开),宽度默认是100%(等于浏览器可视区域宽度),没有margin和padding;
body元素的高度默认是auto,宽度默认是100%,有margin而没有padding;
若想让一个块元素(如div)的高度与屏幕高度自适应,始终充满屏幕,需要从html层开始层层添加height=100%,而又因为html,body元素的width默认就是100%,因此在里面的div 设定width=100%时就能和屏幕等宽。
方法一:继承父元素高度
给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%,其父元素必须有高度
方法二:使用绝对定位(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,如下:
<html>
<body>
新闻热点
疑难解答