在锚点标签上使用CSS Sprites

6

我需要一位CSS大师就最佳结构提供建议。我正在将图标替换为水平“列表”上的精灵图。目前的HTML如下:

<a href="link"><img src="icon" /></a><a href="link_b"><img src="icon"/></a>

所以我用一个精灵图替换它。我正在使用

等等。

<a href="link" class="sprite_img_a"></a><a href="link_b" class="sprite_img_b"></a>

为了做到这一点,我给标签加上了inline-block和width属性。我从来不喜欢inline-block,感觉很笨重。

还有更好的选择吗?(嵌套span或div包装器?)


为什么现在需要使用inline-block?是为了给你的链接设置高度吗? - Paul D. Waite
是的,有些东西需要强制设置高度。 - Karishma
3个回答

8

@karishma: inline-block 是一个不错的选择,如果您不想使用它,可以尝试下面的 CSS。

a.sprite_img_a{
  background:url('image.jpg') no-repeat 0 0 ;
  float:left;
  display:block;
  width:30px;
  height:30px;
}
a.sprite_img_a:hover{
  background-position:-20px 10px ;
}

在背景中使用图标图片是很好的选择,因为它有两个好处:1)可以节省标记空间;2)可以避免Google缓存不需要的图片,这对于SEO来说非常重要。


狡猾。我还没有考虑到这一点。 - Karishma
避免Google缓存不需要的图像。 - Paul D. Waite
@Paul;首先感谢您编辑我的答案,因为我在StackOverflow上遇到了问题。其次,Google只缓存img标签中的图像,而不是背景图像。第三,假设我有一张圆角图片,那么将图片放在img标签中还是背景中更好呢? - sandeep
啊,你不想让一堆图标图片混乱了谷歌。明白了。非常感谢你。 - Paul D. Waite

0

我喜欢你的技术,@sandeep和@hatake-kakashi。有几个可能的改进(虽然可能超出了问题的范围)。尝试将列表和HTML结构化如下:

<style>
/* let your UL and LI handle the link positioning */
ul.sprites {width:somevalue;} /* <--clearfix this someplace cause of the floats inside*/
ul.sprites li {float:left;} /* <- these should collapse to the 30x30 width of the children */
ul.sprites li a {
  display:block;
  /*sprite dimensions*/
  width:30px;
  height:30px;
  background: url('..images/spritesSheet.png') 0 0 no-repeat;
  /*hide link text*/
  text-indent: -9999em
  overflow: hidden;
  text-align: left;
}

/*adjust the background of the single sprite image file*/
ul.sprites a.spriteName1 {background-position:x y;}
ul.sprites a.spriteName1:hover {background-position:x y;}
ul.sprites a.spriteName2 {background-position:x y;}
ul.sprites a.spriteName2:hover {background-position:x y;}
/* etc...*/

</style>
<html>
<ul class="sprites">
    <li><a class="spriteName1" href="#">link1</a></li>
    <li><a class="spriteName2" href="#">link2</a></li>
</ul>
</html>

这样,级联样式表就可以为您工作,列表中的所有链接都可以获得精灵样式而无需冗余的类名。您可以让父元素处理定位。至少我认为是这样的。抱歉,因为我写得有点快又有点随意,所以可能存在语法和伪代码问题。


0

我通常会这样做:

<a class="button sprite" href="#"><span class="sprite">Blah</span></a>

这是 CSS:

.sprite{
    background: url("../images/sprite.png") no-repeat scroll left top transparent;
}
.button{
    background-position: 0 -80px;
    color: white;
    display: block;
    float: left;
    font-size: 0.75em;
    height: 28px;
    line-height: 28px;
    margin-top: 7px;
    overflow: hidden;
    padding-left: 5px;
    text-decoration: none;
    cursor: pointer;
}
.button span{
    background-position: right -80px;
    height: 28px;
    color: white;
    display: block;
    float: left;
    padding: 0 10px 0 5px;
    position: relative;
    text-transform: uppercase;
    text-decoration: none;
}

你会给span显示什么内容? - Karishma
好的。谢谢你的回答。我会尝试其他建议,看看哪个最适合。 - Karishma

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