Gambar Sprite CSS

圖像精靈

圖像精靈是單一圖像中包含的圖像集合。

包含許多圖像的網頁可能需要很長時間才能加載,同時會生成多個伺服器請求。

使用圖像精靈將減少伺服器請求的數量並節約帶寬。

圖像精靈 - 簡單的例子

我們使用以下單幅圖像("navsprites.gif")而不是使用三幅單獨的圖像:

图像導航

通過使用 CSS,我們可以只顯示所需圖像的某部分。

在下面的例子中,CSS 指定了顯示 "navsprites.gif" 圖像的哪部分:

实例

#home {
  width: 46px;
  height: 44px;
  background: url(navsprites.gif) 0 0;
}

Coba Sendiri

Pengertian Contoh:

  • <img id="home" src="trans.gif"> - 只定義小的透明圖像,因為 src 屬性不能為空。而實際顯示的圖像將是我們在 CSS 中指定的背景圖像。
  • width: 46px; height: 44px; - 定義我們要使用的圖像部分
  • background: url(navsprites.gif) 0 0; - 定義背景圖片及其位置(left 0px, top 0px)

圖像精靈 - 創建導航列表

我們希望使用精靈圖片("navsprites.gif")來創建一個導航列表。

我們將使用 HTML 列表,因為它可以是鏈接,同時還支持背景圖片:

实例

#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: 46px;
  background: url('img_navsprites.gif') 0 0;
}
#prev {
  left: 63px;
  width: 43px;
  background: url('img_navsprites.gif') -47px 0;
}
#next {
  left: 129px;
  width: 43px;
  background: url('img_navsprites.gif') -91px 0;
}

Coba Sendiri

Pengertian Contoh:

  • #navlist {position:relative;} - 位置设置为相对,以允许在其中进行绝对定位
  • #navlist li {margin:0;padding:0;list-style:none;position:absolute;top:0;} - 外边距和内边距设置为 0,删除 list-style,并且所有列表项都均为绝对定位
  • #navlist li, #navlist a {height:44px;display:block;} - 所有图片的高度均为 44px

现在开始为每个特定部分设置定位和样式:

  • #home {left:0px;width:46px;} - 一直向左定位,图像宽度 46px
  • #home {background:url(navsprites.gif) 0 0;} - 定义背景图片及其位置(left 0px, top 0px)
  • #prev {left:63px;width:43px;} - 向右定位 63px(#home 宽度 46px + 项目之间的一些额外空间),宽度 43px。
  • #prev {background:url('navsprites.gif') -47px 0;} - 定义背景图片向右 47px(#home 宽度 46px + 1px 分隔线)
  • #next {left:129px;width:43px;} - 向右定位 129px(#prev 开始是 63px + #prev 的宽度是 43px + 多余的空格),宽度 43px。
  • #next {background:url('navsprites.gif') -91px 0;} - 定义背景图片向右 91px(#home 宽度 46px + 1px 分隔线+ #prev 宽度 43px + 1px 分隔线)

图像精灵 - 悬停效果

现在,我们要向导航列表中添加悬停效果。

提示::hover 选择器可用于所有元素,而不仅限于链接。

我们的新图像("navsprites_hover.gif")包含三幅导航图像和三幅用于悬停效果的图像:

图像導航

因为这是一幅图像,而不是六个单独的文件,所以当用户将鼠标悬停在图像上时,不会有加载延迟

我们仅添加三行代码来实现悬停效果:

实例

#home a:hover {
  background: url('navsprites_hover.gif') 0 -45px;
}
#prev a:hover {
  background: url('navsprites_hover.gif') -47px -45px;
}
#next a:hover {
  background: url('navsprites_hover.gif') -91px -45px;
}

Coba Sendiri

Pengertian Contoh:

#home a:hover {background: transparent url('img_navsprites_hover.gif') 0 -45px;} - Kami menetapkan lokasi latar belakang yang sama untuk tiga imej penarik, hanya turun 45 piksel