英文:
How to apply css to each element other than the last, from a specific group
问题
我有类名为SearchHighlightGroup{x}
的跨度,其中x是一个可以具有任何值的正整数。对于给定的x,如果我们将具有类名SearchHighlightGroup{x}
的跨度视为一组,我希望对其中的每一个都应用一种样式,除了最后一个。我希望对每个可能的x都能做到这一点。
例如,如果我有:
<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>
我想将我的样式应用于sp11,sp21 - 以及可能存在的其他跨度。
我可以使用纯CSS实现这个吗?如果不能,那么SCSS可以吗?
英文:
I have spans with className SearchHighlightGroup{x}
where x is a positive integer that can have any value.<br>
For a given x
, if we look at the spans with className SearchHighlightGroup{x}
as a group, I want to apply a style to each one of them, except for the last one. I want that for each x possible.<br>
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 style to sp11, sp21 - and other spans that could be here.<br>
Can I achieve that using pure css? scss if not?
答案1
得分: 1
是的,可以使用新的 nth-child(An + B of S)
来实现,但你需要单独定义每种情况。Sass可以帮助你生成所有这些选择器。
以下是生成选择器的Sass代码示例:
@for $i from 1 through 10 {
span:nth-last-child(n + 2 of [class*=SearchHighlightGroup#{$i}]) {color: red;}
}
请注意,这段代码将生成多个选择器,根据 $i
的值,你可以生成任意数量的选择器。
英文:
Yes it's possible using the new nth-child(An + B of S)
but you have to define each case alone. Sass can help you generate all the selectors
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
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;
}
<!-- language: lang-html -->
<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>
<!-- end snippet -->
Here a Sass code to generate as many selectors as you want:
@for $i from 1 through 10 {
span:nth-last-child(n + 2 of [class*=SearchHighlightGroup#{$i}]) {color: red;}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论