2014-09-10 59 views
2

使用指南針的精靈生成器時,生成器會根據像素創建CSS規則。指南針:將精靈位置導出爲百分比

示例代碼:

示例輸出:

/* line 84, ../../../../../../../../../../../Library/Ruby/Gems/2.0.0/gems/compass-core-1.0.1/stylesheets/compass/utilities/sprites/_base.scss */ 
.sprite-2-00 { 
    background-position: 0 0; 
} 

/* line 84, ../../../../../../../../../../../Library/Ruby/Gems/2.0.0/gems/compass-core-1.0.1/stylesheets/compass/utilities/sprites/_base.scss */ 
.sprite-2-00 { 
    background-position: -244px 0; 
} 

是否有這些可以以百分比來產生,以便它們能夠響應所使用的方式是什麼?

我寫了我自己的,但它在某些瀏覽器中效果不好。這裏是我的方法:

@mixin sprite-percentage-step-generate($steps, $single_image_width) { 
    $total_image_width: ($single_image_width * $steps) - $single_image_width; 
    background-position: 0 0; 
    img { 
     display: none; 
    } 
    @for $i from 0 through ($steps - 1) { 
     $step_width: $i * $single_image_width; 
     &.step-#{$i} { 
      background-position: percentage(($step_width/$total_image_width)) 0; 
      // We include these to see the relation between the percentage and the step count 
      img { 
       display: none; 
      } 
     } 
    } 
} 

也許這不是一個好主意,因爲發電機可能會做一些特殊的優化,使得基於像素的方法效果最好?

同樣,問題是:有沒有辦法讓Compass生成CSS,其中精靈的位置是以百分比形式生成的,而不是以像素形式生成的?

+1

您認爲這會起作用嗎?您無法將像素轉換爲百分比。背景位置屬性的百分比是相對於元素而不是圖像。您需要考慮如何使用純CSS * first *獲得期望的結果,然後詢問如何使用Sass來完成。 – cimmanon 2014-09-10 15:22:01

+0

我不明白這個困惑。我已經有這個工作的版本(由我自己寫的),它的工作原理。之所以這樣做,是因爲如果你知道單個圖像的寬度和每個精靈的步數,你可以將該背景圖像的大小設置爲百分比,然後將'background-position-x'設置爲百分比。有什麼問題?無需將像素轉換爲百分比。 – 2014-09-10 15:26:08

+0

爲了更直接地回答你的問題,使用'background-position-x'是基於設置'background-size'作爲這個精靈中的步數(我忘了提及所有圖像都是相同的寬度)。 – 2014-09-10 15:27:13

回答

2

最後,解決方案是讓所有百分比都沒有小數位或小數點後1位。這在所有瀏覽器中都能很好地工作。

對於具有奇怪數量圖像的精靈(讓我澄清一下,這些精靈都是相同的寬度)解決方案是使圖像更大。例如,如果圖像有17張幻燈片,則圖像可以擴展爲模擬25,從而創建瀏覽器正確渲染的百分比。