How to apply css to every element except the last element in a specific group
P粉596161915
P粉596161915 2023-09-07 20:36:54
0
1
513

I have a span of className SearchHighlightGroup{x} where x is a positive integer that can have any value.

For a given x, if we consider the spans of className SearchHighlightGroup{x} as a group, I want to apply a style to each span in them except the last one. I want every x to be OK.

For example, if I have:

<span class="SearchHighlightGroup1">sp11</span>
<span class="SearchHighlightGroup1">sp12</span>
<span class="SearchHighlightGroup2">sp21</span>
<span class="SearchHighlightGroup2">sp22</span>
<span class="SearchHighlightGroup3">sp31</span>

I want to apply my styles to sp11, sp21 - and other spans that may exist here.

Can I do this using pure css? scss if not?

P粉596161915
P粉596161915

reply all(1)
P粉811349112

Yes, it is possible to use the new nth-child(An B of S), but you must define each case individually. Sass can help you generate all selectors

span:nth-last-child(n + 2 of [class*=SearchHighlightGroup1]) {
  color: red;
}
span:nth-last-child(n + 2 of [class*=SearchHighlightGroup2]) {
  color: blue;
}
span:nth-last-child(n + 2 of [class*=SearchHighlightGroup3]) {
  color: green;
}
<span>ignore</span>
<span class="SearchHighlightGroup1">sp11</span>
<span class="SearchHighlightGroup1">sp12</span>
<span class="SearchHighlightGroup2">sp21</span>
<span class="SearchHighlightGroup2">sp22</span>
<span>ignore</span>
<span>ignore</span>
<span class="SearchHighlightGroup3">sp31</span>
<span>ignore</span>

Here is a Sass code for generating any number of selectors:

@for $i from 1 through 10 {
  span:nth-last-child(n + 2 of [class*=SearchHighlightGroup#{$i}]) {color: red;}
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!