html 和 css 的精灵

Sprites with html and css

我有一些使用 sprite 的代码,它被设计成看起来像水平导航栏。我的问题是:对于下面显示的代码,此方法实际上会导致最终用户下载 png 图像 8 次还是仅下载一次。

如果真的是一次,有更好的方法吗?

CSS代码

#facebook, #twitter, #linkedin, #googleplus {
    width: 64px;
    height: 64px;
    display: inline-block;
}

#facebook {
    background: url("images/sprite.png") 0 0;
}

#twitter {
    background: url("images/sprite.png") -64px 0;
}

#linkedin {
    background: url("images/sprite.png") -128px 0;
}

#googleplus {
    background: url("images/sprite.png") -192px 0;
}

#facebook:hover {
    background: url("images/sprite.png") 0 -64px;
}

#twitter:hover {
    background: url("images/sprite.png") -64px -64px;
}

#linkedin:hover {
    background: url("images/sprite.png") -128px -64px;
}

#googleplus:hover {
    background: url("images/sprite.png") -192px -64px;
}

HTML代码:

<nav>
    <a id="facebook" href="https://www.facebook.com"></a>
    <a id="twitter" href="https://www.twitter.com"></a>
    <a id="linkedin" href="https://www.linkedin.com"></a>
    <a id="googleplus" href="https://plus.google.com"></a>
</nav>

请求只会发生一次,图像会被缓存。图像 将再次重绘 ,但不是通过请求服务器。它只请求服务器一次。但是在主 class 或单个实例中使用 url() 始终是一个好习惯:

#facebook, #twitter, #linkedin, #googleplus {
  background: url("images/sprite.png");
}

此外,最好单独使用background-position,而不是background,也不需要在:hover中再次使用background: url()

只会下载一次,这是使用 CSS 精灵表的主要原因,如果您提供具有正常和悬停状态的每个图标的图像。

不,这就是它的实现方式,您做对了。

资源:

  1. https://css-tricks.com/css-sprites/
  2. http://www.w3schools.com/css/css_image_sprites.asp
  3. https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Images/Implementing_image_sprites_in_CSS

编辑: 正如 Praveen Kumar 提到的,您只需为所有相应的规则编写一次 url() 并使用 background-position 根据您的图像水平或垂直移动图像