CSS雪碧图 - 是否存在简便的方法?

3

例如,我有三个不同的图像作为精灵,带有悬停效果。

精灵示例

<div class="sprite normal"></div>

i dont want this type!

/* small */
    .small{ width:20px; height:20px; }
    .small .sprite{ background:url(sprite.png) 0 0 no-repeat; }
    .small .sprite:hover { background:url(sprite.png) 20px 0 no-repeat; }
/* normal*/
    .normal{ width:50px; height:50px; }
    .normal .sprite{ background:url(sprite.png) 0 0 no-repeat; }
    .normal .sprite:hover { background:url(sprite.png) 50px 0 no-repeat; }
/* big */
    .big{ width:100px; height:100px; }
    .big .sprite{ background:url(sprite.png) 0 0 no-repeat; }
    .big .sprite:hover { background:url(sprite.png) 100px 0 no-repeat; }

有没有简便的方法?谢谢。

对我来说,它看起来非常简短和有组织。我很想知道是否有人有缩短它的建议。+1 - mavrosxristoforos
我可以用jQuery做这个,但我想知道,在CSS中有没有什么方法可以实现.. - avalkab
是的,这是一个好问题,但我认为如果你也应用阿米特·兰詹发布的答案中提到的更改,那么它就相当有组织了。 - mavrosxristoforos
@avalkab,您能否解释一下为什么您想要更少的CSS?我想不出任何理由,这不够用,但显然您认为有理由减少它。 - Stephan Muller
因为我想知道哪个是可能的。 - avalkab
2个回答

1
.sprite{ background:url(sprite.png) 0 0 no-repeat; }

/* small */
    .small{ width:20px; height:20px; }
    .small .sprite:hover { background:url(sprite.png) 20px 0 no-repeat; }

/* normal*/
    .normal{ width:50px; height:50px; }
    .normal .sprite:hover { background:url(sprite.png) 50px 0 no-repeat; }

/* big */
    .big{ width:100px; height:100px; }
    .big .sprite:hover { background:url(sprite.png) 100px 0 no-repeat; }

不要...这和分享我的代码一样。有更简短的方法吗?例如自动感知?... - avalkab
1
不需要多次为background-image和background-repeat设置值 - 如果您只是在特定规则中使用background-position即可。 - CBroe

0
.sprite { background: url('sprite.png') 0 0 no-repeat; }

.small { width: 20px; height: 20px; }
.small:hover { background-position: 20px 0; }

.normal { width: 50px; height: 50px; }
.normal:hover { backgorund-position: 50px 0; }

.big { width: 100px; height: 100px; }
.big:hover { background-position: 100px 0 }

这些都是必需的样式,如果规则不足,你将无法实现目标。


1
嗯,你说得对,@insertusernamehere 最后一个 hover 的确有问题,但我在想原始的 CSS 是否已经有问题了,因为这两个类都在同一个元素上。 - Stephan Muller
@avalkab,你为什么需要更短的CSS呢?也许如果你能解释一下,我们可以给出更全面的答案。 - Stephan Muller
哦,你说得对,这些类都在同一个元素上。我没有看实际的HTML。 - insertusernamehere

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接