如果你可以使用像 SCSS 这样的预处理器:
(更新以实际回答所提出的问题;另请参见实时示例)
// ----------- only things you need to edit { ---------------
$sprite-size: 16px; // standard sprite tile size
$sprite-padding: 0px; // if you have padding between tiles
// ----------- } only things you need to edit ---------------
// basic sprite properties (extension-only class)
%sprite {
width:$sprite-size; height:$sprite-size; // must restrict viewport, otherwise other sprites may "bleed through"
// could set shared standard tilesheet `background-image: url(...)`
// other standard styles, like `display:inline-block` or `position:absolute`
}
// helper for assigning positioning using friendlier numbers like "5" instead of doing the math
@mixin sprite-offset($xoffset:0, $yoffset:0, $increment:$sprite-size, $padding: $sprite-padding) {
background-position: -($xoffset*($increment + $padding)) -($yoffset*($increment + $padding));
}
要从精灵中“浮动”背景,就像@jose-faeti 的回答表明你必须涉及一个占位符元素
<div class="float-bg">
<div class="bg"></div>
<p>Lorem ipsum dolor si...</p>
</div>
风格如下:
.float-bg .bg {
@extend %sprite; // apply sizing properties
background-image: url(...); // actually set the background tiles
@include sprite-offset(4);
// specific configuration per accepted answer
position:absolute;
top: 0;
right: 0;
}
在我原来的答案中,要创建一个按钮列表,您可以:
// list out the styles names for each button
$buttons: 'help', 'font', 'layerup', 'layerdown', 'transform', 'export', 'save', 'clear', 'move-left', 'move-right', 'move-up', 'move-down', 'png', 'jpg', 'svg', 'funky';
.btns > * { @extend %sprite; background-image:... } // apply sizing properties, bg
// autoassigns positioning
@for $i from 1 through length($buttons) {
$btn: nth($buttons, $i);
.btn-#{$btn} {
// @extend .sprite;
@include sprite-offset( $i - 1 );
}
}
然后将从事以下工作:
<ul class="btns">
<li class="btn-help">...</li>
<li class="btn-font">...</li>
<li class="btn-save">...</li>
<li class="btn-export">...</li>
<li class="btn-etc">...</li>
<li class="btn-etc">...</li>
</ul>