Html 使用 CSS ::before 在列表链接之前添加一个小图标

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26441380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 02:54:05  来源:igfitidea点击:

Using CSS ::before to add a small icon before list links

htmlcsscss-content

提问by Bob

The question pretty much explains it but I have list items I want to put a simple diamond icon before them but when I try to use ::before it ends up putting the image above instead of the same line and I can't really seem to find out how to put it right before the list icon on the same line.

这个问题几乎解释了它,但我有列表项,我想在它们之前放一个简单的菱形图标,但是当我尝试使用 ::before 它最终将图像放在上面而不是同一行之前,我似乎真的不能了解如何将它放在同一行的列表图标之前。

Like i said the image is just a small diamond, its 5px by 5px

就像我说的图像只是一个小钻石,它的 5px x 5px

.list-menu::before {
 content: url('../images/menu-icons/image-before.png');
}
<div class="sb-slidebar sb-left sb-style-push">
 <nav>
  <ul>
   <li class="list-menu"><a href="#">Home</a></li>
  </ul>
 </nav>
</div>

回答by James Donnelly

There's no need to use the ::beforepseudo-element here at all. You can just use a background image:

这里根本不需要使用::before伪元素。您可以只使用背景图片:

.list-menu {
  background-image: url('http://placehold.it/16x16');
  background-position: left center;
  background-repeat: no-repeat;
  padding-left: 20px; /* Adjust according to image size to push text across. */
}
<div class="sb-slidebar sb-left sb-style-push">
 <nav>
  <ul>
   <li class="list-menu"><a href="#">Home</a></li>
  </ul>
 </nav>
</div>

回答by Creaforge

Well, list-style-imageis made for that.

嗯,list-style-image就是为此而生的。

Supported since IE 4.0. That should be enough I guess.

从 IE 4.0 开始支持。我想这应该足够了。

ul {
  list-style-image: url('http://placehold.it/12x12');
}
<ul>
  <li> Text content </li>
  <li> Text content </li>
  <li> Text content </li>
</ul>