HTML CSS 图像助手

HTML CSS 图像助手是单个图像中包含的图像集合。
包含许多图像的网页可能需要很长时间才能加载,同时会生成多个服务器请求。
使用图像助手将减少服务器请求的数量并节约带宽。

我们使用以下单幅图像,而不是使用三幅单独的图像:

通过使用 CSS,我们可以仅显示所需图像的某个部分。
在下面的例子中,CSS 指定了显示图像的某一部分,代码如下:

<style>
#home {
  width: 46px;
  height: 44px;
  background: url(/logo.gif) 0 0;
}

#next {
  width: 43px;
  height: 44px;
  background: url(/logo.gif) -91px 0;
}
</style>

<img id="home" src="/img.gif" width="1" height="1">
<img id="next" src="/img.gif" width="1" height="1">

<img id=”home” src=”/img.gif”> – 仅定义小的透明图像,因为 src 属性不能为空。而实际显示的图像将是我们在 CSS 中指定的背景图像。
width: 46px; height: 44px; – 定义我们要使用的图像部分
background: url(/logo.gif) 0 0; – 定义背景图片及其位置(left 0px, top 0px)

现在,我们要向导航列表中添加悬停效果。
提示::hover 选择器可用于所有元素,而不仅限于链接。
我们的新图像包含三幅导航图像和三幅用于悬停效果的图像:

因为这是一幅图像,而不是六个单独的文件,所以当用户将鼠标悬停在图像上时,不会有加载延迟。
我们仅添加三行代码来实现悬停效果,代码如下:

<style>
#navlist {
  position: relative;
}

#navlist li {
  margin: 0;
  padding: 0;
  list-style: none;
  position: absolute;
  top: 0;
}

#navlist li, #navlist a {
  height: 44px;
  display: block;
}

#home {
  left: 0px;
  width: 43px;
  background: url('/logo.gif') 0 0;
}

#prev {
  left: 63px;
  width: 42px;
  background: url('/logo.gif') -47px 0;
}

#next {
  left: 129px;
  width: 42px;
  background: url('/logo.gif') -91px 0;
}

#home a:hover {
  background: url('/logo.gif') 0 -45px;
}

#prev a:hover {
  background: url('/logo.gif') -47px -45px;
}

#next a:hover {
  background: url('/logo.gif') -91px -45px;
}
</style>

<ul id="navlist">
  <li id="home"><a href="/index.asp"></a></li>
  <li id="prev"><a href="/prev.asp"></a></li>
  <li id="next"><a href="/next.asp"></a></li>
</ul>

#home a:hover {background: transparent url(‘img_navsprites_hover.gif’) 0 -45px;} – 我们为所有三个悬停图像指定相同的背景位置,仅向下 45 像素

如果你发现错误或有其他见解,请给www.zhuei.com留言,我们会尽快更新本文!

发表评论

邮箱地址不会被公开。 必填项已用*标注