我知道这个问题有点过时了 - 但这里有一个完整的例子:
HTML:
<div>
<ul class="icon person">
<li>John Doe</li>
<li>Jack Snow</li>
<li>Mary Moe</li>
</ul>
</div>
CSS:
ul.icon {
list-style: none; /* This removes the default bullets */
padding-left: 20px; /* This provides proper indentation for your icons */
}
ul.icon li {
position: relative; /* Allows you to absolutely place the :before element
relative to the <li>'s bounding box. */
}
ul.icon.person li:before {
background: url(/images/ui-icons_888888_256x240.png) -144px -96px;
/* ex: download.jqueryui.com/themeroller/images/ui-icons_888888_256x240.png */
/* The -144px, -96px coordinate is the location of the 16x16 Person icon */
/* The next 2 lines are necessary in order to make the :before pseudo-element
appear, and thereby show it's background, your icon. */
content: '';
display: inline-block;
/* Absolute is always in relation to the nearest positioned parent. In this
case, that's the <li> with _relative_ positioning, above. */
position: absolute;
left: -16px; /* Places the icon 16px left of the <li>'s edge */
top: 2px; /* Adjust this based on your font-size and line-height */
height: 16px; width: 16px; /* jQuery UI icons (with spacing) are 16x16 */
}
这是jsFiddle showing it working。结果将如下所示:
我使用:before 伪元素的原因是您想要使用jQuery-UI 图标——它们以精灵图的形式出现。换句话说 - 所有图标都在单个图像中的网格模式中找到,如下例所示:
来源:http://download.jqueryui.com/themeroller/images/ui-icons_888888_256x240.png
如果您尝试只为该图像制作<li> 的背景,则在不显示所有相邻图标的情况下制作您想要的单个图标会更加复杂。但是,通过使用:before 元素,您可以为图标创建一个较小的16px 和16px 框,从而轻松地缩减为只显示一个图标。
如果您想了解有关 :before 和 :after 伪元素的更多信息,请查看 this fantastic article 作为起点。