Multiple CSS selection with square brackets
I have this piece of code on my website:
#stage-1-picture,
#stage-2-picture,
#stage-3-picture,
#stage-5-picture {
margin-top: 20px;
position: relative;
z-index: 1;
}
I was wondering if there is a way to shorten this multiple choice with square brackets so that I can use some kind of player instead of the numbers 1,2,3,4,5.
Thank!
source to share
Not really, without resorting to some sort of reggex selector. However, this can be done with some CSS3 attribute selectors :
p[id^="item-"][id$="-test"] { color: red; }
<p id="item-1-test">Test 1 (should be red)</p>
<p id="item-1-test">Test 2 (should be red)</p>
<p id="item-1">Without last part (should not be red)</p>
<p id="1-test">Without first part (should not be red)</p>
<p id="different">Totally different (should not be red)</p>
<p id="item--test">Warning! Incorrectly red.</p>
The CSS rule only selects items starting with "item-" and ending with "-test".
That said, I recommend looking at different approaches: whether it's SASS, jQuery, or refactoring your strategy all together: it seems like what you need class="stage-picture"
for your elements ...
source to share
You would probably use preprocessors like SASS or LESS. However, it is much more natural to use classes for your task, since this is exactly what you want: a target set of elements with similar characteristics:
.stage-picture {
margin-top: 20px;
position: relative;
z-index: 1;
}
HTML:
<div class="stage-picture" id="stage-1-picture"></div>
<div class="stage-picture" id="stage-2-picture"></div>
<!-- etc ... -->
source to share