使用Css Sprites和背景位置 [英] Using Css Sprites and background position

查看:145
本文介绍了使用Css Sprites和背景位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个div元素,宽度为200像素,高度为200像素。我需要一个小图像出现在div的右上角。如何通常会这样做

I have a div element, say of width 200px and height 200px. I need a small image to appear on the top right corner of the div. How one would normally do it would be with

background: url(/images/imagepath.png) top right;

但是问题是,我从sprite加载图像,当我使用像



However the problem is, I am loading the image from a sprite and when I use something like

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

sprite似乎没有从正确的位置选择。 sprite的其他部分被加载。是否可以从sprite加载图像,并使用background-position属性。先感谢...

the sprite doesnt seem to pick it from the right location. Some other part of the sprite is loaded. Is it possible to load an image from sprite and use the background-position attribute as well. Thanks in advance...

推荐答案

您需要以两种不同的方式指定元素位置和背景位置的坐标。

You need to specify the coordinates for your element position and the background position in two different ways.

#yourimage {
  background-image: url(/web/images/imagepath.png);
  /* background coordinates */
  background-position: -215px -759px;

  /* element coordinates */
  position:absolute;
  left: 0;  /* 0px from the left */
  top:  0;  /* 0px from the top  */
}

使用 background-position 指定背景坐标。对于您的元素的坐标,您需要设置属性。

With the background-position you specify the background coordinates. For the coordinates of your element, you need to set the left and right properties.

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

Keep in mind that in order to use sprites, your element must be of the correct size. The image you are using as a background must have enough space to cover the width and height of the element, not more, otherwise you will see more than one image from your sprites image.

如果您要显示小于元素的图片,则需要在大图片中包含较小的元素。

If you want to display a image smaller than your element, you need a smaller element inside the big one.

<div id="container">
  <div class="background"></div>
  my content here
</div>

然后在您的CSS中

#container {
  position:relative;
  width: 200px;  /* size of your big element */
  height: 200px;
}
#container .background {
  background: url(/web/images/imagepath.png) -215px -759px;
  width:  50px; /* width and height of the sprite image you want to display */
  height: 50px;
  position: absolute;
  top: 0;
  left: 0;
}

这篇关于使用Css Sprites和背景位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆