Compass Sprites 使用與問題解決
什麼是Sprites? 請參考W3C CSS Image Sprites 範例
簡單來說,就是使用一張大圖片,利用位移方式顯示想要的圖案 好處就是減少HTTP Request次數(一張圖片就是發起一次HTTP Request)
網路上有現成的工具可以使用 CSS Sprites generator 這個工具非常方便,可以自動幫你產生圖檔和CSS文件
先前介紹的SCSS Framework - Compass,也提供的好用的方法可以使用 Compass Sprites Document
簡單說明使用方式
1.config.rb設定檔內 => images_dir 指定位置內新增一資料夾 example => arrows 2.將要合併的圖檔arrows資料夾內
- images_dir/arrows/up.png
- images_dir/arrows/down.png
- images_dir/arrows/left.png
- images_dir/arrows/right.png
3.scss檔案輸入
- @import "arrows/*.png";
- @include all-arrows-sprites; => @include all-[folder-name]-sprites
4.對應的CSS應該會產生以下內容
.arrows-sprite, .arrows-down, .arrows-left, .arrows-right, .arrows-up { background: url('/images/arrows-sef3b99158d.png') no-repeat; }
.arrows-down { background-position: 0 -32px; }
.arrows-left { background-position: 0 -96px; }
.arrows-right { background-position: 0 -64px; }
.arrows-up { background-position: 0 0; }
可能遇到的問題
1.路徑問題 => windows環境下,由於正(\)反(/)斜線問題,導致路徑問題
解決方式: compass watch path => path使用linux路徑表示
example : d:\www\project1 => d:/www/project1
2.CSS樣式圖片路徑不準確 .arrows-sprite, .arrows-down, .arrows-left, .arrows-right, .arrows-up { background: url('/images/arrows-sef3b99158d.png') no-repeat; }
解決方式: config.rg 加入參數 => relative_assets = "true"
在HTML使用方式 <div class="arrows-down"></div>