每日一个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是減少圖片資源請(qǐng)求次數(shù)的首選方法。將一些背景圖片組合到一張圖片中,并在css文件中使用background-image和background-position屬性展示需要的圖片部分。
以上是雅虎web性能優(yōu)化最佳實(shí)踐中的Minimize HTTP Requests(減少http請(qǐng)求次數(shù))中的一個(gè)策略,使用css sprites。
并不是所有的圖片都需要組合到一起,需要組合的圖片:ico、圖標(biāo)等小型圖片。大型的圖不需要應(yīng)用css sprites。
實(shí)現(xiàn)方式
1.首先把需要的圖標(biāo)利用ps等工具合成到一張圖片中,例如
2.編寫(xiě)css樣式在編寫(xiě)展示圖片的時(shí)候要注意兩點(diǎn):
由于css sprites主要的應(yīng)用是展示圖標(biāo)等小型圖片,通常需要與其他元素展示在一行中,所以在編寫(xiě)css代碼時(shí)有一個(gè)很方便的技巧是將容器的display屬性設(shè)置為inline-block,既可以方便的設(shè)置容器的寬和高又可以與其他需要的元素共處一行,例如:
<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> 復(fù)制代碼效果如下
其核心代碼為 /* 設(shè)置容器的高度,寬度和圖片 */ .ico {height: 16px;width: 16px;display: inline-block;background-image: url("images/ico.png"); } /* 定位顯示的背景 */ .ico-alert {background-position: 0 0; } 復(fù)制代碼background-position 有三種定位方式
- 關(guān)鍵詞定位top, right, bottom, left, center選擇其中的兩個(gè)作為其參數(shù),若只有一個(gè)參數(shù)則認(rèn)為第二個(gè)為center
- 百分比定位
- 像素定位
百分比定位和像素定位可以混用
百分比定位和像素定位:其參數(shù)可正可負(fù)。當(dāng)為正數(shù)時(shí),代表背景圖片作為對(duì)象盒子背景圖片時(shí)靠左和靠上多少距離多少開(kāi)始顯示背景圖片;當(dāng)為負(fù)數(shù)時(shí)代表背景圖片作為盒子對(duì)象背景圖片,將背景圖片拖動(dòng)超出盒子對(duì)象左邊多遠(yuǎn),拖動(dòng)超出盒子對(duì)象上邊多遠(yuǎn)開(kāi)始顯示此背景圖片。一般都會(huì)使用負(fù)數(shù),比較符合人的使用習(xí)慣
轉(zhuǎn)載于:https://juejin.im/post/5d06093f6fb9a07ed657d1f0
總結(jié)
以上是生活随笔為你收集整理的每日一个css效果之css sprites的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: go使用之-编译约束
- 下一篇: sudo apt install ...