How can I prefix ordered list item numbers with a static string using CSS?

╄→гoц情女王★ 提交于 2020-01-09 05:22:36

问题


I want this HTML...

<ol style="list-style:decimal;">
<li>Apples</li>
<li>Oranges</li>
</ol>

...to render like this

Q1. Apples
Q2. Oranges

In other words, I want the auto-generated numbers to be prefixed with the static string "Q".

I've tried CSS like this:

ol li:before
{
  content:"Q";
}

But that produces 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 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.).


回答1:


The only pure CSS way is with counters:

ol {
    counter-reset: item;
    list-style-type: decimal;
}

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.

By the way, it's decimal, not numbered.




回答2:


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;
}

JS Fiddle demo.



来源:https://stackoverflow.com/questions/5568229/how-can-i-prefix-ordered-list-item-numbers-with-a-static-string-using-css

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!