每日一个css效果之css sprites

为什么要是用css sprites

CSS Sprites are the preferred method for reducing the number of image requests. Combine your background images into a single image and use the CSS background-image and background-position properties to display the desired image segment.

使用css sprites是减少图片资源请求次数的首选方法。将一些背景图片组合到一张图片中,并在css文件中使用background-imagebackground-position属性展示需要的图片部分。

以上是雅虎web性能优化最佳实践中的Minimize HTTP Requests(减少http请求次数)中的一个策略,使用css sprites。

并不是所有的图片都需要组合到一起,需要组合的图片:ico、图标等小型图片。大型的图不需要应用css sprites。

实现方式

1.首先把需要的图标利用ps等工具合成到一张图片中,例如

2.编写css样式

在编写展示图片的时候要注意两点:

  1. 图片的定位
  2. 图片容器的宽和高

由于css sprites主要的应用是展示图标等小型图片,通常需要与其他元素展示在一行中,所以在编写css代码时有一个很方便的技巧是将容器的display属性设置为inline-block,既可以方便的设置容器的宽和高又可以与其他需要的元素共处一行,例如:

<!DOCTYPE html>
<html lang="zh">
<head>
	<meta charset="UTF-8">
	<title>home</title>

	<style>
		.ico {
			height: 16px;
			width: 16px;
			display: inline-block;
			background-image: url("images/ico.png");
		}
		.ico-alert {
			background-position: 0 0;
		}
		.ico-word {
			background-position: -24px 0;
		}
		.ico-excel {
			background-position: -48px 0;
		}
		.ico-ppt {
			background-position: -72px 0;
		}
		.ico-pdf {
			background-position: -96px 0;
		}
		.ico-txt {
			background-position: -120px 0;
		}
		a {
			display: inline-block;
			width: 35px;
			text-align: center;
			margin: 5px;
			text-decoration: none;
		}
	</style>
</head>
<body>
	<div>
		<span class="ico ico-alert"></span><a href="#">alert</a>
		<span class="ico ico-word"></span><a href="#">word</a> <br>
		<span class="ico ico-excel"></span><a href="#">excel</a>
		<span class="ico ico-ppt"></span><a href="#">ppt</a> <br>
		<span class="ico ico-pdf"></span><a href="#">pdf</a>
		<span class="ico ico-txt"></span><a href="#">txt</a>
	</div>
</body>
</html>
复制代码

效果如下

其核心代码为

/* 设置容器的高度,宽度和图片 */
.ico {
	height: 16px;
	width: 16px;
	display: inline-block;
	background-image: url("images/ico.png");
}
/* 定位显示的背景 */
.ico-alert {
	background-position: 0 0;
}
复制代码

background-position 有三种定位方式

  • 关键词定位top, right, bottom, left, center选择其中的两个作为其参数,若只有一个参数则认为第二个为center
  • 百分比定位
  • 像素定位

百分比定位和像素定位可以混用

百分比定位和像素定位:其参数可正可负。当为正数时,代表背景图片作为对象盒子背景图片时靠左和靠上多少距离多少开始显示背景图片;当为负数时代表背景图片作为盒子对象背景图片,将背景图片拖动超出盒子对象左边多远,拖动超出盒子对象上边多远开始显示此背景图片。一般都会使用负数,比较符合人的使用习惯

转载于:https://juejin.im/post/5d06093f6fb9a07ed657d1f0

猜你喜欢

转载自blog.csdn.net/weixin_34244102/article/details/93181212