CSS实现网页背景图片自适应全屏

HTML:css

<!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>title</title> </head> <body> <div class="wrapper"> <!--背景图片--> <div id="web_bg" style="background-image: url(./img/bg.jpg);"></div> <!--其余代码 ... --> </div> </body> </html>

CSS:html

#web_bg{ position:fixed; top: 0; left: 0; width:100%; height:100%; min-width: 1000px; z-index:-10; zoom: 1; background-color: #fff; background-repeat: no-repeat; background-size: cover; -webkit-background-size: cover; -o-background-size: cover; background-position: center 0; }

下面,咱们来分析一下,css中每句代码的做用是什么:web

position:fixed; top: 0; left: 0;

这三句是让整个div固定在屏幕的最上方和最左方chrome

width:100%; height:100%; min-width: 1000px;

上面前两句是让整个div跟屏幕实现如出一辙的大小,从而达到全屏效果,而min-width是为了实现让屏幕宽度在1000px之内时,div的大小保持不变,也就是说在这种状况下,缩放屏幕宽度时,图片不要缩放(只有在1000px之内才有效)。浏览器

z-index:-10;

这个的目的是让整个div在HTML页面中各个层级的下方,正常状况下,第一个建立的层级z-index的值是0,因此若是咱们这里写成-1也能够实现,不过这里写-10是确保整个div在最下面,由于若是页面中层级太多了,有的时候用-1不必定在最下面,但若是写成-100这样大数字的也没有什么意义。用index:-10 以此能达到看上去像背景图片,实际上是一个最普通的div,只是层级关系变了,才让人看上去看是背景图片。app

 background-repeat: no-repeat;

上面这个是背景不要重复ui

background-size: cover; -webkit-background-size: cover; -o-background-size: cover;

上面三句是一个意思,就是让图片随屏幕大小同步缩放,可是有部分可能会被裁切,不过不至于会露白,下面两句是为chrome和opera浏览器做兼容。url

background-position: center 0;

上面这句的意思就是图片的位置,居中,靠左对齐。spa

 

出处:https://www.jianshu.com/p/5480cd1a5d89code

相关文章
相关标签/搜索