首頁技術(shù)文章正文

CSS精靈圖有什么作用?怎樣添加精靈圖

更新時間:2023-05-04 來源:黑馬程序員 瀏覽量:

IT培訓(xùn)班

CSS 精靈,也叫 CSS Sprites,是一種網(wǎng)頁圖片應(yīng)用處理方式。把網(wǎng)頁中一些背景圖片整合到一張圖片文件中,再用background-position 精確的定位出背景圖片的位置。

精靈圖的作用是減少服務(wù)器被請求次數(shù),減輕服務(wù)器的壓力,提高頁面加載速度。
精靈圖提高頁面加載速率

實現(xiàn)步驟:

1. 創(chuàng)建盒子,盒子尺寸與小圖尺寸相同

2. 設(shè)置盒子背景圖為精靈圖

3. 添加 background-position 屬性,改變背景圖位置,使用 PxCook 測量小圖片左上角坐標(biāo),取負(fù)數(shù)坐標(biāo)為 background-position 屬性值(向左上移動圖片位置)。

案例:京東服務(wù)

下面我們以京東服務(wù)的圖標(biāo)為例。

1683183593944_京東服務(wù).png
添加上圖中的精靈圖,需要的代碼如下:

<style>
  * {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
  }

  li {
    list-style: none;
  }

  .service {
    margin: 100px auto;
    width: 1190px;
    height: 42px;
    /* background-color: pink; */
  }

  .service ul {
    display: flex;
  }

  .service li {
    display: flex;
    padding-left: 40px;
    width: 297px;
    height: 42px;
    /* background-color: skyblue; */
  }

  .service li h5 {
    margin-right: 10px;
    width: 36px;
    height: 42px;
    /* background-color: pink; */
    background: url(./images/sprite.png) 0 -192px;
  }

  .service li:nth-child(2) h5 {
    background-position: -41px -192px;
  }

  .service li:nth-child(3) h5 {
    background-position: -82px -192px;
  }

  .service li:nth-child(4) h5 {
    background-position: -123px -192px;
  }

  .service li p {
    font-size: 18px;
    color: #444;
    font-weight: 700;
    line-height: 42px;
  }
</style>


分享到:
在線咨詢 我要報名
和我們在線交談!