Max*_*uza 18 css css-sprites background-position
我有一个div元素,比如宽度为200px,高度为200px.我需要一个小图像出现在div的右上角.人们通常如何做到这一点
background: url(/images/imagepath.png) top right;
Run Code Online (Sandbox Code Playgroud)
但问题是,我正在从精灵加载图像,当我使用类似的东西时
background: url(/web/images/imagepath.png) -215px -759px top right;
Run Code Online (Sandbox Code Playgroud)
精灵似乎没有从正确的位置选择它.精灵的其他部分被加载.是否可以从精灵加载图像并使用background-position属性.提前致谢...
Jos*_*eti 29
您需要以两种不同的方式指定元素位置和背景位置的坐标.
#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 */
}
Run Code Online (Sandbox Code Playgroud)
用background-position
你指定背景坐标.对于元素的坐标,您需要设置left
和right
属性.
请记住,为了使用精灵,您的元素必须具有正确的大小.您用作背景的图像必须有足够的空间来覆盖元素的宽度和高度,而不是更多,否则您将从精灵图像中看到多个图像.
如果要显示小于元素的图像,则需要在较大元素内部使用较小的元素.
<div id="container">
<div class="background"></div>
my content here
</div>
Run Code Online (Sandbox Code Playgroud)
然后在你的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;
}
Run Code Online (Sandbox Code Playgroud)
ava*_*all 13
你可以:before
像这样使用伪类:
.element:before {
content:"";
position:absolute;
right:0;
top:0;
width:20px;
height:20px;
background: url(/web/images/imagepath.png) -215px -759px;
}
Run Code Online (Sandbox Code Playgroud)
但这支持得很差.
我的建议是在你的包裹中制作另一个元素,并且像上面一样绝对定位它:before
,例如真实的div
编辑
这里描述了在盒角中使用精灵的另一种棘手方法.