Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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).

like image 247
Triynko Avatar asked Apr 06 '11 14:04

Triynko


People also ask

How do I make a numbered list in CSS?

Ordered list starts with the <ol> tag. The list item starts with the <li> tag and will be marked as numbers, lowercase letters uppercase letters, roman letters, etc. The default numbers for list items. For creating an ordered list with numbers, use the <ol> tag attribute type.


2 Answers

The only pure CSS way is with 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.

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

like image 86
BoltClock Avatar answered Nov 05 '22 14:11

BoltClock


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.

like image 45
David Thomas Avatar answered Nov 05 '22 12:11

David Thomas