CSS使用精靈圖的方法:首先使用background-image屬性導(dǎo)入精靈圖;然后利用background-repeat:no-repeat設(shè)置圖像不重復(fù);最后使用background-position屬性設(shè)置圖像初始位置,進(jìn)行精確定位。
本教程操作環(huán)境:windows7系統(tǒng)、CSS3&&HTML5版、Dell G3電腦。
CSS Sprite是什么?
CSS Sprite直譯為“CSS精靈”,也被稱為通常被解釋為“CSS圖像拼合”或“CSS貼圖定位”,是一種網(wǎng)頁圖片應(yīng)用處理方式。其實(shí)就是把多張小圖片整合到一張圖片中去,再利用CSS的“background-image
”,“background-repeat
”,“background-position
”進(jìn)行背景定位,background-position
可以用數(shù)字能精確的定位出背景圖片在布局盒子對(duì)象位置。
優(yōu)點(diǎn):
減少網(wǎng)頁http請(qǐng)求,加快頁面加載速度,提高頁面的性能(適合小圖)。
比如頁面上使用到很多icon的圖,如果頁面一張張去請(qǐng)求這些圖片的時(shí)后那http請(qǐng)求就會(huì)很多,這時(shí)候把這些圖片合并為一張的話,頁面就只需要加載一次了,減少了http請(qǐng)求帶來的性能消耗。如下圖:
圖片整合原則:
-
邊切圖邊整合。
-
定位時(shí)避免使用bottom,right等,用具體的數(shù)值,為了避免當(dāng)你的寬度或高度上擴(kuò)展sprites圖時(shí)出現(xiàn)位置的錯(cuò)誤。
-
將小圖標(biāo)預(yù)留足夠的空間,因?yàn)槭褂眠@些圖標(biāo)元素通常會(huì)有大量的內(nèi)容而且可能需要擴(kuò)展的間距,以至于其它的圖片可能會(huì)意外出現(xiàn)在本區(qū)域內(nèi)。一般的情況下,會(huì)將這些小圖標(biāo)整合到文件的最右側(cè)。
-
單張整合好的sprite圖片在100KB以內(nèi)。
-
按分類整合圖片。
-
為了方便計(jì)算尺寸,一般情況會(huì)將sprites圖的坐標(biāo)計(jì)算成整數(shù)倍。
實(shí)現(xiàn)代碼:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>sprite精靈圖使用</title> <style type="text/css"> ol, ul ,li{list-style:none}; body, p, ul, li {margin:0; padding:0;} ul li { float: left; background-color: #63caac; color: #fff; padding: 5px 10px; margin-right: 10px; } li:hover{background-color:#347764;} ul.sprite li span{display: block;} ul.sprite li span.l1{background-position:0 0;} ul.sprite li span.l2{background-position:-64px 0;} ul.sprite li span.l3{background-position:-128px 0;} ul.sprite li span.l4{background-position:-192px 0;} ul.sprite li span{width:64px;padding-top:5px;height:64px;overflow:hidden;background:url(img.png) no-repeat;} </style> </head> <body> <ul class="sprite"> <li><span class="l1"></span></li> <li><span class="l2"></span></li> <li><span class="l3"></span></li> <li><span class="l4"></span></li> </ul> </body> </html>
推薦學(xué)習(xí):《css視頻教程》