使用Css Sprites和背景位置

前端之家收集整理的这篇文章主要介绍了使用Css Sprites和背景位置前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个div元素,宽度为200px,高度为200px。我需要一个小图像出现在div的右上角。通常会做什么呢?
  1. background: url(/images/imagepath.png) top right;

但问题是,我正在从一个精灵加载图像,当我使用类似的东西

  1. background: url(/web/images/imagepath.png) -215px -759px top right;

精灵似乎没有从正确的位置选择它。 sprite的其他一部分被加载。是否可以从sprite加载图像,并使用background-position属性。提前致谢…

解决方法

您需要以两种不同的方式指定元素位置和背景位置的坐标。
  1. #yourimage {
  2. background-image: url(/web/images/imagepath.png);
  3. /* background coordinates */
  4. background-position: -215px -759px;
  5.  
  6. /* element coordinates */
  7. position:absolute;
  8. left: 0; /* 0px from the left */
  9. top: 0; /* 0px from the top */
  10. }

使用背景位置指定背景坐标。对于元素的坐标,您需要设置左右属性

请记住,为了使用精灵,您的元素必须具有正确的大小。您用作背景的图像必须有足够的空间来覆盖元素的宽度和高度,而不是更多,否则您将从您的精灵图像中看到多个图像。

如果要显示小于元素的图像,则需要较大的元素。

  1. <div id="container">
  2. <div class="background"></div>
  3. my content here
  4. </div>

然后在你的CSS

  1. #container {
  2. position:relative;
  3. width: 200px; /* size of your big element */
  4. height: 200px;
  5. }
  6. #container .background {
  7. background: url(/web/images/imagepath.png) -215px -759px;
  8. width: 50px; /* width and height of the sprite image you want to display */
  9. height: 50px;
  10. position: absolute;
  11. top: 0;
  12. left: 0;
  13. }

猜你在找的CSS相关文章