【问题标题】:Can you style ordered list numbers?您可以设置有序列表编号的样式吗?
【发布时间】:2014-06-29 21:09:38
【问题描述】:

我正在尝试为有序列表中的数字设置样式,我想添加背景颜色、边框半径和颜色,以便它们与我正在使用的设计相匹配:

我想这是不可能的,我必须为每个数字使用不同的图像,即

ol li:first-child {list-style-image:url('1.gif')};
ol li:nth-child(2) {list-style-image:url('2.gif');} 
etc...

有没有更简单的解决方案?

【问题讨论】:

标签: html css html-lists sprite


【解决方案1】:

2021年更新,可以在最近的浏览器中使用::marker伪元素选择器:https://developer.mozilla.org/en-US/docs/Web/CSS/::marker

 li::marker {
   color: red;
 }
 li {
   color: blue;
 }
<ol>
  <li>item</li>
  <li>item</li>
  <li>item</li>
  <li>item</li>
</ol>

【讨论】:

  • 酷!这在 Chrome 和 Safari 上有效吗?
  • @Pixelomo 是的,但对可以设置和不可以设置的样式有一些限制。对于像颜色这样简单的东西,它工作得很好。 caniuse.com/css-marker-pseudo
  • 根据 CanIUse 的判断,截至 2022 年,似乎不再有使用限制,所有现代浏览器似乎都很好地支持它。
【解决方案2】:

您可以使用CSS counters:before 伪元素来做到这一点:

 ol {
   list-style: none;
   counter-reset: item;
 }
 li {
   counter-increment: item;
   margin-bottom: 5px;
 }
 li:before {
   margin-right: 10px;
   content: counter(item);
   background: lightblue;
   border-radius: 100%;
   color: white;
   width: 1.2em;
   text-align: center;
   display: inline-block;
 }
<ol>
  <li>item</li>
  <li>item</li>
  <li>item</li>
  <li>item</li>
</ol>

【讨论】:

  • counter-reset: item; 应该放在 ol 块中,否则计数器不会在嵌套
      中重置。
  • 一个不错的解决方案,但是当li元素的主体超过一行时,渲染效果如何?
  • 我认为,就像在stackoverflow.com/questions/13354578/… 中一样,您可以使用例如` margin-left: -2.0em;宽度:-2.0em;`
  • 50% 的值 border-radius(而不是 100%)足以得到一个圆圈。 (参见,例如,Lea Verou,“The curious case of border-radius:50%”,2010 年 10 月 30 日。)
  • @cmhughes - 如果你想这样做,你会给出li position: relative;,然后对于:before,你会给出position: absolute;,然后使用topleft 完全按照您的喜好定位。
【解决方案3】:

我一直在寻找不同的东西,并在 CodePen 找到了这个示例;

试试这个:http://codepen.io/sawmac/pen/txBhK

body {
  font-size: 1.2em;
  font-family: "Helvetica Neue", Helvetica, sans-serif;
  margin: 50px;
}
.custom-counter {
  margin: 0;
  padding: 0;
  list-style-type: none;
}
.custom-counter li {
  counter-increment: step-counter;
  margin-bottom: 5px;
}
.custom-counter li::before {
  content: counter(step-counter);
  margin-right: 20px;
  font-size: 80%;
  background-color: rgb(180, 180, 180);
  color: white;
  font-weight: bold;
  padding: 3px 8px;
  border-radius: 11px;
}
<ol class="custom-counter">
  <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>

【讨论】:

    猜你喜欢
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-07
    • 1970-01-01
    • 1970-01-01
    • 2019-05-06
    • 2012-02-23
    • 1970-01-01
    相关资源
    最近更新 更多