Tôi biết câu hỏi này là một chút out-of-date - nhưng đây là một ví dụ làm việc đầy đủ:
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 */
}
Đây là một jsFiddle showing it working. Kết quả sẽ giống như thế này:

Lý do mà tôi đã sử dụng pseudo-yếu tố :before
là bạn đang muốn sử dụng các biểu tượng jQuery-UI - mà đến dưới hình thức của một bản đồ ma. Nói cách khác - tất cả các biểu tượng được tìm thấy trong một mô hình lưới trong một hình ảnh duy nhất, như trong ví dụ này:
Nguồn: http://download.jqueryui.com/themeroller/images/ui-icons_888888_256x240.png

Nếu bạn cố gắng chỉ làm cho nền của <li>
hình ảnh đó, nó sẽ phức tạp hơn để làm cho biểu tượng duy nhất mà bạn muốn xuất hiện mà không hiển thị tất cả các nước láng giềng của nó. Bằng cách sử dụng phần tử :before
, bạn có thể tạo một hộp nhỏ hơn, 16px
bởi 16px
cho biểu tượng và do đó dễ dàng cắt xuống để chỉ hiển thị một biểu tượng.
Nếu bạn muốn tìm hiểu thêm về :before
và :after
thành phần giả, hãy xem this fantastic article làm điểm bắt đầu.
Nguồn
2013-04-23 17:32:02