是否可以将 Sprite 图标定位为元素的背景?
我有一个文件“icons.png”,其中包含几个图标。我想选择其中一个作为元素的背景。
通常我会用
. Sprite {
背景:url('imgs/icons.png') 不重复 0 -21px;
宽度:17px;
高度:10px;
并将此类用于按钮等...
问题是我有一个文本输入,我想修改它的占位符 .First I did this,如果我使用的文件是图标本身,它会完美地工作
:-webkit-input-placeholder{ background: url('singleIcon.jpg') center right no-repeat; }
但现在我想使用一个包含更多图标的文件。 是否可以使用这样的东西?
:-webkit-input-placeholder{ background: url('imgs/icons.jpg') center right no-repeat; }
最后一行代码的问题是它会选择我所有的图像(当然包含我想在网站上使用的我的所有图标),我只想选择一部分该图像的(我想使用的图标)
最佳答案
实际上, Sprite 仅用作背景(或者您必须设置某种复杂的裁剪)。
你所要做的是将元素的大小设置为你要显示的 Sprite 的同一部分,背景的位置等于 Sprite 中图标的 x 和 y 坐标,从左上角。
取自 this nice article 的示例:
“元素 2”为 116x48,从 12px(x 坐标)和 70px(y 坐标)开始。
所以你的元素的 CSS 应该是:
.element {
width:116px;
height:48px;
background:url(sprites.png) -12px -70px no-repeat;
}
但是,如果您的元素比上述尺寸高/宽怎么办?然后,您必须用足够的透明/空白空间隔离该图标,以便其他图标不会显示。
如果你抬头看Facebook sprites ,您会注意到其中有些很长,有些成组,有些孤立。您必须针对每种情况调整 Sprite 。
编辑:好的,我得到了你的实际需要。
使用 input
并不容易,因为您不能在其上使用伪元素。这里有一个解决方法。
首先,将输入包装在一个 div 中:
<div class="inputWrapper">
<input type="text" placeholder="placeholder text">
</div>
然后添加一些CSS:
div.inputWrapper {
position:relative; /* that's important */
float:left; /* or display:inline-block; */
}
div.inputWrapper:after {
background:#000 url(sprites.png) 0 -2px no-repeat; /* adjust background position */
content:" "; /* whitespace needed for the pseudo-element to be displayed */
position:absolute;
top:1px; right:2px; /* some room for the borders */
width:16px; /* icon width */
height:18px; /* icon height */
}
div.inputWrapper input {
padding-right:16px; /* so the text won't go behind the icon */
}
我知道这很复杂,但另一种方法是创建另一个 http 请求......选择权在你。
关于CSS Sprite 作为背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12837562/