移动端页面不满一屏时实现一屏背景(图)

61 阅读1分钟

一般,元素都是由元素内容撑开,但是开发过程中难免会遇到内容不满一屏,但是背景需要撑开一屏的情况(例如:列表页就一行数据,但是这页有个背景,总不能背景在这一条数据背后戛然而止,再往下就什么都没有了),查看前人经验,一般有以下几种解决方法:

1. 设置min-height

     给父元素设置一个min-height: 100%;

     照理说这样设置会自动撑开至屏幕大小,但假如内容复杂点,设置了别的样式,会导致这样并不能起到作用,而是需要给min-height设置一个具体的值(如5rem);

      另外如果直接子元素有下margin,就会在部分手机上触发BFC。

2. 单独固定一个空div,设置背景色,z-index:-100;

     如:     

     <div class="content">你的内容</div>

     <div class="background"></div>

     .background{

           width:100%;

           height:100%;

           position:fixed;

           top:0;

           background:#f00;

          z-index:-100;

      }

3. 使用伪元素 (好用!!!)

<div class="content">
    内容内容。。。。。
</div>
.content::before{
    content:" ";
    position:absolute;
    left:0;
    right:0;
    top:0;
    bottom:0;
    background-color:#0ff;
    z-index:-100;
}