Felipe Cerda
Felipe Cerda

Reputation: 490

"Dynamic" CSS id names? How to add them to the CSS file?

I have DIV ids in an application that are generated dynamically, with an ID at the end. For example: <div id="vote_score_72">, <div id="vote_score_73">, <div id="vote_score_74"> and so on.

How can I write that id in the CSS file so I can apply a style to it?

Upvotes: 15

Views: 29932

Answers (2)

David Thomas
David Thomas

Reputation: 253308

Further to the suggestion that you should use classes for this functionality (and you should), you can, instead, use the attribute-value-begins-with selector (this may not be the formal name):

div[id^=vote_score] {
    color: #f00;
    /* and so on... */
}

JS Fiddle demo.


Edited to add a link to the Quirksmode.org's compatibility tables for advanced attribute selectors.

References:

Upvotes: 33

JMax
JMax

Reputation: 26591

You should add a common class to all these elements and use this class in your CSS.

Classes are the best way to handle common style for different elements.

Upvotes: 2

Related Questions