Marius Schulz
Marius Schulz

Reputation: 16470

How to access an element's class value via CSS

How can I access the numbers (1 and 2 in the example below) at the end of the paragraph's class string via CSS?

<p class="cooking-step-1">
<!-- Second step ... -->
</p>

<p class="cooking-step-2">
<!-- Second step ... -->
</p>

I can access these paragraphs via the following selector: p[class^="cooking-step-"]
I want to add the paragraph's number in front of the text inside of it via the CSS content property. How do I achieve this?

Upvotes: 0

Views: 397

Answers (2)

derekerdmann
derekerdmann

Reputation: 18262

Since you're working with set steps and trying to number them, then you should probably try to use an ordered list instead. The ol indicates that the items belong in the given order, and it provides numbering without any extra work!

If you really want to use CSS, then counters are what you're looking for. In the containing element for these paragraphs, apply the style counter-reset: step. Then for your paragraph tags use:

p:before {   
    counter-increment: step;   
    content: counter(step)". ";   
}  

This should work in modern browsers, but because of simplicity and legacy browser support, I think you'll be happier with just an ordered list.

Upvotes: 1

janmoesen
janmoesen

Reputation: 8020

That is possible using counters. However, browser support is spotty and I think the spec changed for CSS3.

Basically, you do not even need the cooking-step-N class. If you use a class like cooking-step, you can simply let the engine do the counting for you. Increment it on each .cooking-step and use its counter() for the content.

Upvotes: 2

Related Questions