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

百分比定位和像素定位:其參數可正可負。當爲正數時,表明背景圖片做爲對象盒子背景圖片時靠左和靠上多少距離多少開始顯示背景圖片;當爲負數時表明背景圖片做爲盒子對象背景圖片,將背景圖片拖動超出盒子對象左邊多遠,拖動超出盒子對象上邊多遠開始顯示此背景圖片。通常都會使用負數,比較符合人的使用習慣

相關文章
相關標籤/搜索