Using regular expression in css?


I have an html page with divs that have id(s) of the form s1, s2 and so on.

<div id="sections">
   <div id="s1">...</div>
   <div id="s2">...</div>

I want to apply a css property to a subset of these sections/divs (depending upon the id). However, every time I add a div, I have to add the css for the section separately like this.


Is there something like regular expressions in css that I can use to apply style to a set of divs.

This question is tagged with css regex

~ Asked on 2012-01-17 23:48:39

The Best Answer is


You can manage selecting those elements without any form of regex as the previous answers show, but to answer the question directly, yes you can use a form of regex in selectors:

#sections div[id^='s'] {
    color: red;  

That says select any div elements inside the #sections div that have an ID starting with the letter 's'.

See fiddle here.

W3 CSS selector docs here.

~ Answered on 2012-01-18 00:06:39


As complement of this answer you can use $ to get the end matches and * to get matches anywhere in the value name.

Matches anywhere: .col-md, .left-col, .col, .tricolor, etc.


Matches at the beginning: .col-md, .col-sm-6, etc.


Matches at the ending: .left-col, .right-col, etc.


~ Answered on 2018-04-11 18:56:54

Most Viewed Questions: