DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS詳解
用 Gulp 自動產生 CSS Sprites 雪碧圖與 SCSS 樣式
編輯:CSS詳解     

手工維護雪碧圖是一場惡夢:新增一個圖示要重算座標、刪掉一個要重排整張圖。把這件事交給 Gulp,只要把圖丟進資料夾,座標與樣式全部自動產生。

Sass 端:三個 mixin 就夠用

先準備好接收資料的 mixin。這段樣板會搭配 handlebars 風格的模板一起使用:

@mixin sprite-width($sprite) {
  width: nth($sprite, 3);
}

@mixin sprite-height($sprite) {
  height: nth($sprite, 4);
}

@mixin sprite-position($sprite) {
  $sprite-offset-x: nth($sprite, 1);
  $sprite-offset-y: nth($sprite, 2);
  background-position: $sprite-offset-x $sprite-offset-y;
}

@mixin sprite($sprite) {
  @include sprite-position($sprite);
  @include sprite-width($sprite);
  @include sprite-height($sprite);
}

每個 sprite 都是一個由四個值組成的 list:x 座標、y 座標、寬、高,用 Sass 的 nth() 函式取值即可。三個小 mixin 負責組裝成完整的 background 設定。

模板:把 mixin 包成可讀的樣式

{{#sprite}}
{{class}} {
  background-repeat: no-repeat;
  overflow: hidden;
  border: none;
  background: url('{{{escaped_image}}}?v=#{$version}');
  @include inline-block();
  vertical-align: middle;
  font-style: normal;
  color: $icon-font-color;
}
{{/sprite}}

{{#items}}
.{{name}} {
  @include sprite(${{name}});
}
{{/items}}

這個模板做兩件事:先產生一個共用的基礎 class(處理背景不重複、行內塊對齊、顏色等共通設定),再為每個圖示產生對應的 class 並引入座標。

執行與輸出

搞定,就是這麼簡單。把圖片丟進 icon 資料夾、執行 gulp sprites,就會產出一張雪碧圖 icon.png 與對應的 SCSS 樣式檔 _icon.scss。再建一個 watch 任務監聽該資料夾,就能即時重建。

產生的 _icon.scss 大致長這樣:

$icon-QQ:    -262px -161px 60px 60px;
$icon-email: -332px -161px 60px 60px;
$icon-skype:   -5px  -252px 60px 60px;
$icon-phone:  -75px  -252px 60px 60px;

@mixin sprite-width($sprite) {
  width: nth($sprite, 3);
}

@mixin sprite-height($sprite) {
  height: nth($sprite, 4);
}

@mixin sprite-position($sprite) {
  $sprite-offset-x: nth($sprite, 1);
  $sprite-offset-y: nth($sprite, 2);
  background-position: $sprite-offset-x $sprite-offset-y;
}

@mixin sprite($sprite) {
  @include sprite-position($sprite);
  @include sprite-width($sprite);
  @include sprite-height($sprite);
}

.icon {
  background-repeat: no-repeat;
  overflow: hidden;
  border: none;
  background: url('#{$icon-sprite-path}/icon.png?v=#{$version}');
  @include inline-block();
  vertical-align: middle;
  font-style: normal;
  color: $icon-font-color;
}

.icon-QQ    { @include sprite($icon-QQ); }
.icon-email { @include sprite($icon-email); }
.icon-skype { @include sprite($icon-skype); }
.icon-phone { @include sprite($icon-phone); }

座標是負值,因為背景圖要往左上「推」才能把目標圖示推進視窗裡。URL 後面加上 ?v=#{$version} 是為了在部署時透過版本號強制更新瀏覽器快取。

使用方式

需要哪個圖示,就掛上兩個 class:

<i class="icon icon-QQ"></i>

基礎 class 負責共通樣式,修飾 class 負責座標,職責切得很乾淨。

還需要雪碧圖嗎

值得想一想。雪碧圖的價值在 HTTP/1.1 時代很明確——合併請求。但在 HTTP/2 多重承載上線後,多個小檔案可以並行傳輸,雪碧圖的優勢被大幅削弱,反而失去了單檔快取與按需載入的彈性。

今天的替代方案:單純的裝飾性圖示用 SVG sprite(<symbol> 加 <use>)或 icon font;需要多色、複雜的圖示則直接引入個別 SVG 檔。若你的專案仍需支援舊環境或圖示數量固定在幾十個以內,自動化的 sprite 流程依然是一個可靠選擇——重點是別再手算座標了。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved