精灵的宽度取决于精灵中图标(图像)的数量:一个图标(通常)应该是它必须覆盖的按钮宽度的 100%。所以对于 8 个图标:
background-position: 800%;
图标 i(第一个:i=1,第二个 i=2 等)与图标总数 n 的偏移量计算如下:
偏移量百分比 = (i - 1 / n - 1) * 100%
因此对于精灵第一行中的第 5 个图标 8,偏移量 = (5-1/8-1)*100% = 57,142 %
background-position: 57.142 top;
SASS 混合:
@mixin background-position($number: 1){
$total: 8; /* The number of icons in the sprite, placed next to one another */
background-size: percentage($total); /* Results in 800% for 8 icons */
background-position: percentage( ($number - 1)/($total - 1) ) top; /* My sprite has the default state in the top row, :active states in the bottom */
}
使用像 SASS 这样的预处理器可以让您灵活地在稍后阶段向精灵添加图标,而无需更改所有先前计算的背景位置。
当然,此解决方案适用于任何具有背景图像的元素,而不仅仅是按钮。