我可以使用 CSS 为任何元素添加项目符号吗?

新手上路,请多包涵

很简单的问题,但我不确定这是否可能。我想在所有 <h1> 元素中添加一个图像作为项目符号。我知道我可以通过以下方式实现这一目标:

 <span class='bullet'></span><h1>My H1 text here</h1>

与CSS:

 .bullet{
    background: url('bullet.png') no-repeat;
    display:inline-block;
    vertical-align: middle;
    background-size:100%;
    height:25px;
    width:25px;
    margin-right: 5px;
}

但是有没有一种自动的方法来做同样的事情?我在想这样的事情:

 h1{
    list-style-image: url('bullet.png');
}

但这似乎只适用于 <ul> 元素。我真的不想在 <span> 元素之前到处粘贴 <h1> 元素。有任何想法吗?

原文由 Sablefoste 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 338
2 个回答

虽然您可以使用 :before 伪选择器在您的元素前面添加“-”或“•”字符,但它并不能真正使您的元素表现得像一个要点。您的元素可能看起来像一个要点,但这只是一个肮脏的 hack,真的,应该避免!

要使您的元素 (1) 看起来像一个项目符号点并且 (2) 表现得像一个项目符号点,您应该将该元素的 — display 设置为 list-item 。 Optionally, you can also set list-style-type (default : disc ) and list-style-position (default : outside ) attributes to modify the behavior / look - 和您的列表项的感觉。

如果您的元素跨越多行, list-style-position 应该是默认值 outside 如果您希望所有行都与项目符号点的右侧对齐。然而,在这种情况下,您可能看不到实际的项目符号点,因为它位于元素内容的左侧。如果发生这种情况,您只需添加一个左边距以将元素的内容向右移动,您的项目符号点就会显示出来。


示例 1

 h1 {
    display: list-item; /* This has to be "list-item"                                          */
    margin-left : 1em;  /* If you use default list-style-position 'outside', you may need this */
}
 <h1>
  Your H1 text should go here. If it consists of multiple
  lines, the left alignment of all lines is the same.
</h1>
<h1>
  Here's another item.
</h1>

例 2

 h2 {
    display: list-item;          /* This has to be "list-item"                                               */
    list-style-type: square;     /* See https://developer.mozilla.org/en-US/docs/Web/CSS/list-style-type     */
    list-style-position: inside; /* See https://developer.mozilla.org/en-US/docs/Web/CSS/list-style-position */
}
 <h2>
  Your H2 text should go here.
</h2>
<h2>
  Note that, if you have multiple lines, only the first
  line is aligned to the right of the bullet point when
  using list-style-position 'inside'. Subsequent lines
  are left aligned with the left of the bullet point.
</h2>

原文由 John Slegers 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题