如何为有序列表编号的CSS样式?

时间:2019-07-28 15:31:05

标签: html css

我尝试使用CSS更改“有序列表”数字的样式,但结果是错误的。

<ol>
  <li>This is the first item</li>
  <li>This is the second item</li>
  <li>This is the third item</li>
  <li>This is the fourth item</li>
  <li>This is the fifth item</li>
  <li>This is the sixth item</li>
</ol>

CSS

ol li {
  counter-increment: step-counter;
  margin-bottom: 10px;
  list-style-type: none;
}

ol li::before {
  content: counter(step-counter);
  margin-right: 5px;
  font-size: 80%;
  background-color: rgb(0,200,200);
  color: white;
  font-weight: bold;
  padding: 3px 8px;
  border-radius: 15px;
}

上面的代码显示2个列表编号(一个默认值,另一个是我定义的样式)。输出就像

    1. 这是我的第一项
    1. 这是我的第二项

所以,为什么它会出现两次。请帮忙获得一次(第二个是我定义的样式)

1 个答案:

答案 0 :(得分:1)

custom-counter是无效的选择器,即使它是有效的,也不会指向任何内容。只需删除整个规则集,然后将list-style-type: none;添加到<ol>中即可,如下所示:

ol {list-style-type: none;}

position:relative分配给所有<li>,并将position:absolute分配给每个li::before,以便对从文本到项目符号的所有距离进行精细控制。

li {
  position: relative;
...
}

li::before {
...
  position: absolute;
  top: -1px;
  /* Adjust < -number | number+ > */
  left: -32px;
...

:root {
  font: 400 16px/1.25 Verdana
}

ol {
  list-style-type: none;
}

ol li {
  counter-increment: step-counter;
  position: relative;
  margin: 10px 0 0 0;
}

ol li::before {
  content: counter(step-counter);
  display: block;
  position: absolute;
  top: -1px;
  /* Adjust < -number | number+ > */
  left: -32px;
  width: 1.25rem;
  height: 1.25rem;
  line-height: 1.25rem;
  background-color: rgb(0, 200, 200);
  color: white;
  font-weight: bold;
  font-size: 0.8rem;
  text-align: center;
  border-radius: 15px;
}
<ol>
  <li>This is the first item</li>
  <li>This is the second item</li>
  <li>This is the third item</li>
  <li>This is the fourth item</li>
  <li>This is the fifth item</li>
  <li>This is the sixth item</li>
</ol>