我对此也做了一些研究。这个要点是我想出来的:https://gist.github.com/apauly/7917906
Update:
该解决方案取决于三个关键部分:
- 刻度宽度
- 刻度高度
- 获取背景位置
0.获取完整精灵和单个图标的尺寸:
$icon-file: sprite-file($map, $icon);
$icon-width: image-width($icon-file);
$icon-height: image-height($icon-file);
$sprite-file: sprite-path($map);
$sprite-width: image-width($sprite-file);
$sprite-height: image-height($sprite-file);
1.考虑一个显示精灵作为背景的 div。放background-size: 100%;
确保背景精灵覆盖 div 的整个宽度。
如果有人会使用width: 100%;
,结果会是这样的:
+----------------+
|--| |
|----------------|
|--------| | <--- This is the sprite image we want to display
|------| |
+----------------+
所以我们需要放大我们的背景以获得像这样的东西:(div应该有overflow:hidden
though)
+----------------+
|---------| |
|-----------------------|
|----------------| | <---
|-------------| |
+----------------+
要实现这一点,只需将完整精灵的宽度除以单个图标的宽度即可:
width:percentage($sprite-width / $icon-width);
2.这个基本上是受到 tkenny 的一篇博客文章的启发:http://inspectelement.com/tutorials/a-responsive-css-background-image-technique/
生成的sass代码是这样的:
display: block;
height: 0;
padding-bottom: percentage($icon-height / $icon-width);
background-size: 100%;
3.剩下的只是一些基本的数学计算,以相对值的形式计算精灵内部图标的顶部间距:
获取距顶部的空间(以像素为单位)(负值):
$space-top:floor(nth(sprite-position($map, $icon), 2));
Sass 需要一个 px 值
@if $space-top == 0 {
$space-top: 0px
}
用百分比设置背景位置:
background-position:0 percentage(
-1 * $space-top / ( $sprite-height - $icon-height )
);