CSS实现自适应不同大小屏幕的背景大图的两种方法(转自简书)

时间:2024-01-02 16:30:56

CSS实现自适应不同大小屏幕的背景大图的两种方法

一张清晰漂亮的背景图片能给网页加分不少,设计师也经常会给页面的背景使用大图,我们既不想图片因为不同分辨率图片变形,也不希望当在大屏的情况下,背景有一块露白,简而言之,就是实现能自适应屏幕大小又不会变形的背景大图,而且背景图片不会随着滚动条滚动而滚动。

用CSS实现真的很简单很简单,下面我们来看一下第一种方法具体的代码:

HTML代码:

 <!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代码:

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

你看,代码就是这么简单。
下面,我们来分析一下,css中每句代码的作用是什么:

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

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

   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,只是层级关系变了,才让人看上去看是背景图片。

 zoom: 1;

这个的目的是为了兼容IE浏览器

 background-repeat: no-repeat;

上面这个是背景不要重复

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

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

   background-position: center 0;

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

第二种方法的代码

HTML代码如下:

 <div class="about-me">
![](./images/about-me.jpg)
<a href="http://iheima.com" class="introduction">
<h3>About me</h3>
</a>
</div>

css代码如下:

 .about-me {
position: relative;
min-width: 1480px;
width: 100%;
height: 520px;
overflow: hidden;
img.me {
position: absolute;
bottom:;
left:;
width: 100%;
height: auto;
min-height: 520px;
z-index:;
}
.introduction {
display: block;
position: absolute;
left:;
bottom:;
right:;
top:;
width: 100%;
height: 100%;
color: #fff;
background: rgba(0, 0, 0, .6);
z-index:;
cursor: pointer;
h3 {
margin: 100px auto 140px;
width: 170px;
height: 90px;
line-height: 90px;
font-size: 36px;
border-bottom: 2px solid #0b6d99;
}
}
}