Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

css

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?

like image 891
Felipe Cerda Avatar asked Nov 06 '11 16:11

Felipe Cerda


2 Answers

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:

  • CSS3 Attribute-selectors, at Sitepoint.com.
  • Attribute selectors, at CSS3.info
  • Attribute Selectors, at the Mozilla Developers Network.
like image 60
David Thomas Avatar answered Oct 11 '22 19:10

David Thomas


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.

like image 35
JMax Avatar answered Oct 11 '22 19:10

JMax