每日一个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-image和background-position屬性展示需要的圖片部分。
以上是雅虎web性能優化最佳實踐中的Minimize HTTP Requests(減少http請求次數)中的一個策略,使用css sprites。
并不是所有的圖片都需要組合到一起,需要組合的圖片:ico、圖標等小型圖片。大型的圖不需要應用css sprites。
實現方式
1.首先把需要的圖標利用ps等工具合成到一張圖片中,例如
2.編寫css樣式在編寫展示圖片的時候要注意兩點:
由于css sprites主要的應用是展示圖標等小型圖片,通常需要與其他元素展示在一行中,所以在編寫css代碼時有一個很方便的技巧是將容器的display屬性設置為inline-block,既可以方便的設置容器的寬和高又可以與其他需要的元素共處一行,例如:
<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
總結
以上是生活随笔為你收集整理的每日一个css效果之css sprites的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: go使用之-编译约束
- 下一篇: sudo apt install ...