如何使用 CSS 为有序列表项编号添加静态字符串前缀?
我希望这个 HTML:
<ol style="list-style:decimal;">
<li>Apples</li>
<li>Oranges</li>
</ol>
像这样呈现:
Q1。苹果
Q2。橙子
即,我想在每个数字前加上“Q”前缀。
我已经尝试过像这样的CSS:
ol li::before {
content: "Q";
}
但呈现如下:
1. Q苹果
2.Q橙子
我也尝试过使用list-style: numbered inside;
,但这只是将列表向右移动,结果相同。我找不到任何方法来引用这些数字以便使用 CSS 设置它们的样式。这看起来是一个简单、常见的场景,但我找不到任何方法用简单的 CSS 来完成它(没有 CSS 计数器、JavaScript 等)。
I want this HTML:
<ol style="list-style:decimal;">
<li>Apples</li>
<li>Oranges</li>
</ol>
to render like this:
Q1. Apples
Q2. Oranges
Ie, I want to prefix "Q" to each number.
I've tried CSS like this:
ol li::before {
content: "Q";
}
but that renders like this:
1. QApples
2. QOranges
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 any way to reference the numbers in order to style them with CSS. 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).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
唯一的纯 CSS 方法是使用 计数器:
除了使用CSS 计数器(专为此类用例设计!)或 JavaScript。
顺便说一下,它是
十进制
,而不是编号
。The only pure CSS way is with counters:
You cannot achieve this besides using CSS counters (which were designed specifically for such use cases!) or JavaScript.
By the way, it's
decimal
, notnumbered
.有一种脆弱非计数器方法,但它很容易崩溃:
JS Fiddle演示。
There is a, fragile, non-counter method, but it's prone to breaking:
JS Fiddle demo.
鉴于此 HTML:
您可以 (1) 使用
@counter-style
CSS at-rule:(参见W3C:CSS 计数器样式级别 3:3.1.7. 从现有计数器样式构建:扩展系统。)或 (2) 使用 CSS 计数器 和
::marker
CSS 伪元素:无论哪种方式,您都可以设置
list-style-position
CSS 属性 通过list-style
CSS速记属性到值inside
,以使渲染的HTML看起来像BoltClock的答案。HTML 编辑:我删除了
style="list-style:decimal;"
因为我认为这是ol
元素的默认设置。我添加了class="q"
以便样式仅适用于特定列表。我将每个 li 元素缩进两个空格,因为我更喜欢这种样式。Given this HTML:
you could (1) use the
@counter-style
CSS at-rule:(See W3C: CSS Counter Styles Level 3: 3.1.7. Building from Existing Counter Styles: the extends system.) or (2) use CSS counters and the
::marker
CSS pseudo-element:Either way, you could set the
list-style-position
CSS property via thelist-style
CSS shorthand property to the valueinside
in order to make the rendered HTML appear like that of BoltClock's answer.HTML edits: I removed
style="list-style:decimal;"
because I think that's the default forol
elements. I addedclass="q"
so that the styling only applies to specific lists. I indented eachli
element by two spaces because I prefer that style.