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

//css
#s1{
...
}

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


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;
}
<div id="sections">
  <div id="s1">one</div>
  <div id="s2">two</div>
  <div id="s3">three</div>
  <div id="t1">four</div>
</div>

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.


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.

[class*="col"]

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

[class^="col-"]

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

[class$="-col"]

An ID is meant to identify the element uniquely. Any styles applied to it should also be unique to that element. If you have styles you want to apply to many elements, you should add a class to them all, rather than relying on ID selectors...

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

and

.sec {
    ...
}

Or in your specific case you could select all divisions inside your parent container, if nothing else is inside it, like so:

#sections > div {
    ...
}