我有一个div元素,宽度为200px,高度为200px。我需要一个小图像出现在div的右上角。通常会做什么呢?
- background: url(/images/imagepath.png) top right;
但问题是,我正在从一个精灵加载图像,当我使用类似的东西
- background: url(/web/images/imagepath.png) -215px -759px top right;
精灵似乎没有从正确的位置选择它。 sprite的其他一部分被加载。是否可以从sprite加载图像,并使用background-position属性。提前致谢…
解决方法
您需要以两种不同的方式指定元素位置和背景位置的坐标。
- #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 */
- }
使用背景位置指定背景坐标。对于元素的坐标,您需要设置左右属性。
请记住,为了使用精灵,您的元素必须具有正确的大小。您用作背景的图像必须有足够的空间来覆盖元素的宽度和高度,而不是更多,否则您将从您的精灵图像中看到多个图像。
如果要显示小于元素的图像,则需要较大的元素。
- <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;
- }