Html 如何使用 CSS 使用静态字符串作为有序列表项编号的前缀?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5568229/
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
How can I prefix ordered list item numbers with a static string using CSS?
提问by Triynko
I want this HTML...
我想要这个 HTML...
<ol style="list-style:decimal;">
<li>Apples</li>
<li>Oranges</li>
</ol>
...to render like this
...渲染成这样
Q1. Apples
Q2. Oranges
一季度。苹果
Q2。橙子
In other words, I want the auto-generated numbers to be prefixed with the static string "Q".
换句话说,我希望自动生成的数字以静态字符串“Q”为前缀。
I've tried CSS like this:
我试过这样的 CSS:
ol li:before
{
content:"Q";
}
But that produces this:
但这会产生这个:
- QApples
- QOranges
- 苹果
- Q橙子
I've also tried using "list-style:numbered inside;", but that just shifts the list to the right with the same results. I can't find a way to reference the auto-generated number elements in any way to add CSS styling information to them. This seems like such a simple, common scenario, yet I can't find any way to accomplish it with straightforward CSS (without CSS counters, JavaScript, etc.).
我也试过使用“list-style:numbered inside;”,但这只是将列表向右移动,结果相同。我找不到以任何方式引用自动生成的数字元素来向它们添加 CSS 样式信息的方法。这似乎是一个如此简单、常见的场景,但我找不到任何使用简单的 CSS(没有 CSS 计数器、JavaScript 等)来完成它的方法。
回答by BoltClock
The only pure CSS way is with counters:
唯一的纯 CSS 方式是使用counters:
ol {
counter-reset: item;
list-style-type: none;
}
ol li:before {
content: 'Q' counter(item, decimal) '. ';
counter-increment: item;
}
You cannot achieve this besides using CSS counters (which were designed specifically for such use cases!) or JavaScript.
除了使用 CSS 计数器(专为此类用例设计!)或 JavaScript 之外,您无法实现这一点。
By the way, it's decimal
, not numbered
.
顺便说一下,它是decimal
,不是numbered
。
回答by David says reinstate Monica
There is a, fragile, non-counter method, but it's prone to breaking:
有一个脆弱的非反方法,但它很容易被破坏:
ol {
list-style-type: decimal;
margin: 0 0 0 2em;
}
li {
position: relative;
}
ol li:first-letter {
color: #f90;
float: left;
position: relative;
margin-left: -2em;
}