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

标签 html css css-selectors html-lists listitem

很简单的问题,但我不确定是否可行。我想在所有 <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> 之前的元素无处不在元素。有什么想法吗?

最佳答案

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

要使您的元素 (1) 看起来像一个元素符号点并且 (2) 表现得像一个元素符号点,您应该将该元素的 display 设置为 list-item。或者,您还可以设置 list-style-type(默认:disc)和 list-style-position(默认:outside ) 属性来修改列表项的行为/外观。

如果您的元素跨越多行,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>

关于html - 我可以使用 CSS 为任何元素添加元素符号吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32039846/

相关文章:

javascript - 骰子游戏 - 需要根据情况掷更多骰子

php - 对来自 MySQL 的数据进行排序并将其插入到 HTML 表中

html - 容器不适合屏幕和 flex-direction : row not working properly

css - 固定 header ,不在正文填充上使用硬值

html - 将更改的属性设置为 span

jquery - 如何根据href属性找到页面中的链接?

html - 随着内部 Div 的扩展,使 HTML 列变宽

javascript - 阻止输入提交html代码/脚本

html - CSS忽略子元素但不忽略文本

html - 当输入 div 获得焦点时显示 div