se7*_*7en 11 css css-selectors
是否可以编写CSS规则来选择没有特定类的元素的第一个子元素?
例:
<div>
<span class="common-class ignore"></span>
<span class="common-class ignore"></span>
<span class="common-class"></span>
<span class="common-class"></span>
</div>
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我想选择第一个span没有课程ignore.我试过这个,但似乎没有用:
.common-class:first-child:not(.ignore) {
...some rules...
}
Run Code Online (Sandbox Code Playgroud)
更新:
如果我向一个名为父div的类添加一个类,那么parent-classJukka建议的选择器的修改版本可以工作,除非第一个span类ignore在第一个没有之后.上述选择器如下:
.parent-class > .common-class.ignore + .common-class:not(.ignore) {
...some rules...
}
Run Code Online (Sandbox Code Playgroud)
Bol*_*ock 14
这个问题类似于带有类的第一个元素的CSS选择器,除了没有类的第一个元素.如上所述,:first-child:not(.ignore)表示一个元素,它是其父元素的第一个子元素,并且没有类"ignore",而不是与选择器的其余部分匹配的第一个子元素.
你可以使用我在我对链接问题的回答中描述的兄弟组合器的覆盖技术,用包含类选择器的:not()伪类替换类选择器:
.common-class:not(.ignore) {
/* Every span without class .ignore, including the first */
}
.common-class:not(.ignore) ~ .common-class:not(.ignore) {
/* Revert above declarations for every such element after the first */
}
Run Code Online (Sandbox Code Playgroud)
这将选择带有和没有类的所有跨度..common-class.ignore
span.common-class:not(.ignore) {
color: blue;
}
Run Code Online (Sandbox Code Playgroud)
但是,因为我们只想选择第一个,你可以覆盖~选择器后面的兄弟姐妹.
span.common-class:not(.ignore) ~ span {
color: black; /* or color: inherit; */
}
Run Code Online (Sandbox Code Playgroud)
如果您已经在使用jQuery,那么也可以使用它
$("span.common-class:not(.ignore):first").css('color', 'blue');
Run Code Online (Sandbox Code Playgroud)
不,这是不可能的.选择器:first-child:not(.ignore)选择一个元素,该元素是其父元素的第一个子元素,不属于类ignore.没有"第一类"选择器,也没有"第一类"选择器.
您可以使用选择器.ignore + :not(.ignore),但它匹配任何不在类中ignore的元素并紧跟在该类中的元素之后.但它匹配太多,而不仅仅是第一个这样的元素.根据标记结构,此选择器可能仍适用于特定情况,即使它不是所要求的一般问题的答案.