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!

+3


source to share


3 answers


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>
      

Run codeHide result




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

+2


source


You need to go with the sassas as Suresh said. A solution with sass would be:

%temp {
  margin-top: 20px;
  position: relative;
  z-index: 1;
}

@for $i from 1 through 5 {

  #stage-#{$i}-picture {
    @extend %temp;
  }
}

      



Example: http://sassmeister.com/gist/904fb5c267e5ddfe0c8a

+1


source


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

      

0


source







All Articles