每日一个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

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

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

并非全部的图片都须要组合到一块儿,须要组合的图片: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>
复制代码

效果以下 ui

css sprites效果
其核心代码为

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

background-position 有三种定位方式url

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

百分比定位和像素定位能够混用spa

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

相关文章
相关标签/搜索