一、前言
在实际的前端开发工作中,我们经常会使用html+css做一些页面的布局,写一个完整的网页。而在各种网页中,往往少不了图片。图片几乎是每个网页中不可或缺的部分。缺少了图片的衬托,网页似乎缺少了一种视觉美感。
而在css中就有一种处理图片的方式,也就是以背景图片的方式将需要的图片引入到网页中的具体位置。掌握背景图片的使用也就显得十分的关键了。操作背景图片的属性有很多,这里就不一一的赘述了,主要说一下背景图片属性中的backgroun-size这个属性。很多人在使用的过程中会忽略其中的一个小细节,特别是很多的前端初学者。接下来带你揭秘这个细节。接着往下看吧。
二、background-size的使用细节
要说的细节就是,background-size必须要写在backgroun-imge属性后面才有效果。也就是要先引入背景图片,再设置背景图片的大小才可以,这个顺序不能乱,你若不信,给你验证一下。
示例一:background-size写在背景图片引入之前无效
html代码:
<body>
<div class="box"></div>
</body>
css代码:
<style>
* {
margin: 0px;
padding: 0px;
}
.box {
width: 400px;
height: 400px;
margin: 20px auto;
/*background-size: 50% 50%;*/ /* background-size:背景图片引入之前不起作用 */
background: url(./image/风景01.jpg) no-repeat;
background-size: 50% 50%; /* background-size:背景图片引入之后有效 */
}
</style>
效果展示:
实例二:这是很多初学者容易犯的错误
比如我们要使用一张精灵图实现这样的一个效果
html代码:这个并没有什么问题
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
但是很多人处理css代码是这样的(不建议)
<style>
* {
margin: 0px;
padding: 0px;
}
ul {
width: 500px;
margin: 20px auto;
}
ul li {
list-style: none;
float: left;
width: 32px;
height: 32px;
margin-left: 20px;
background: url(./image/bg .png) no-repeat 0 0;
background-size: 32px auto;
}
ul li:nth-child(2) {
background: url(./image/bg .png) no-repeat 0 -32px;
}
ul li:nth-child(3) {
background: url(./image/bg .png) no-repeat 0 -64px;
}
ul li:nth-child(4) {
background: url(./image/bg .png) no-repeat 0 -96px;
}
ul li:nth-child(5) {
background: url(./image/bg .png) no-repeat 0 -128px;
}
</style>
这个时候会发现,除了第一个可以实现具体的需求效果之外,其余的都不行,如下图:
这又是为什么呢?很多初学者百思不得其解。其实说说到底,还是backgroun-size的原因
在这个案例中如果重新引入了背景图(虽然是多余的操作),要达到需求,必须再引入背景图片的后面再写一次backgroun-size才有效果。
但是这个案例中,不建议这样处理,这样处理也没啥意义,重复代码太多,只是为了阐述background-size的使用细节才这样写的,也是很多初学者小白容易犯的一个错误。下面给出一个推荐的写法。
推荐的写法:
案例开头已经说过了,是使用精灵图来做的,所以五个图标唯一不同的地方应该是精灵图的位置,其他的都是相同的。这个时候只需要改变一下精灵图的位置就可以了,其他的相同的部分可以写在一起。
<style>
* {
margin: 0px;
padding: 0px;
}
ul {
width: 500px;
margin: 20px auto;
}
/*所有li相同的样式属性*/
ul li {
list-style: none;
float: left;
width: 32px;
height: 32px;
margin-left: 20px;
background: url(./image/bg .png) no-repeat 0 0;
background-size: 32px auto;
}
/*每个li背景图片的位置不同,改变每一个li图片的位置即可*/
ul li:nth-child(2) {
background-position: 0px -32px;
}
ul li:nth-child(3) {
background-position: 0px -64px;
}
ul li:nth-child(4) {
background-position: 0px -96px;
}
ul li:nth-child(5) {
background-position: 0px -128px;
}
</style>
三、总结
对背景图片的操作在前端页面布局中很常用。对于background-size这个使用细节,一定要掌握。以上分享希望对大家有所帮助。