CSS 没有同级选择器
考虑以下 html:
<div>
<div class="iwant" />
<div class="idontwant" />
</div>
<div>
<div class="iwant" />
</div>
我对一个选择器感兴趣(用于抓取内容,因此我无法修改 html),它将选择所有不具有类 idontwant
iwant >。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
没有同级选择器可以按类匹配(或不匹配)元素。
我能想到的最接近的选择器是
但是这个选择器意味着除了
div class="iwant"
之外不能有任何其他元素作为父div
的子元素,无论类型或类别。不过,这可能会满足您的需求,具体取决于 HTML 的结构,因此值得一试。但是,如果类名对您来说是个问题,那么可能没有太多解决方案,因为 CSS 中没有按类过滤的:only-of-class
伪类并忽略其余部分。There is no sibling selector to match elements (or not) by class.
The closest selector I can think of is
But this selector means that there cannot be any other elements besides that
div class="iwant"
as children of the parentdiv
, regardless of type or class. This may fulfill your need depending on the structure of your HTML though, so it's worth a try. If class names are a problem for you, though, then there probably isn't much of a solution, because there isn't an:only-of-class
pseudo-class in CSS which filters by class and ignores the rest.如果有人仍然需要这个,我找到了这个答案。基于它和:不是伪类,初始要求可以使用类似的方法来完成:
这种方法比一般的同级组合器有一个优势:它还向后匹配,意思是这样的:(
所以如果你首先有
.idontwant
元素 -> case这将被一般兄弟组合器忽略)说明:
div:has(+ .idontwant)
将匹配任何与idontwant
类具有直接同级的div
div:not (:has(+ .idontwant))
匹配任何与idontwant
类没有直接兄弟的div
idontwant
类的直接同级。选择器非常奇怪而且很大,但它完成了工作,而且我认为在某些(特定)情况下它是非常需要的。
编辑(来自评论):
如果有人需要仅在元素具有特定同级(或没有)时对其进行样式设置,您仍然可以使用 :有伪类来完成它(检查代码片段):
If anyone still needs this, I found this answer . Based on it and on :not pseudo-class, the initial requirement can be accomplished using something like:
This approach has an advantage over the general sibling combinator: It also matches backwards, meaning something like:
(so if you have the
.idontwant
element first -> case which would be ignored by the general sibling combinator)Explanation:
div:has(+ .idontwant)
would match anydiv
that has a direct sibling with the classidontwant
div:not(:has(+ .idontwant))
matches anydiv
that doesn't have a direct sibling with classidontwant
idontwant
for the class we want.The selector is quite weird and big, but it does the job, and I think there are (specific) cases where it is quite needed.
Edit (from comments):
If anyone needs to style an element only if it has a specific sibling (or if it doesn't) you can still use the :has Pseudo-class to accomplish it (check snippet):
没有负同级 CSS 选择器。使用同级选择器设置新样式,然后在
.idontwant
处重置样式:There's no negative-sibling CSS selector. Use the sibling selector to set new styles, then reset the styles at the
.idontwant
:如果没有特定的同级项目,就没有好的方法来定位项目。但您可以使用
.iwant:last-child
来定位没有后续同级的项目。示例: http://codepen.io/martinkrulltott/pen/YyGgde
There's no good way to target an item without a specific sibling item. But you can use
.iwant:last-child
to target items that doesn't have a subsequent sibling.Example: http://codepen.io/martinkrulltott/pen/YyGgde
如果您想要的元素始终是最后一个子元素,这也可能会有所帮助:
This also might be helpful - if the element you want is always last-child: