如何在样式定义中排除所有孩子的班级 [英] How to exclude a class with all children in style definition

查看:73
本文介绍了如何在样式定义中排除所有孩子的班级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似的文件

<div>
 <div class="abc">
  <div>
   <!--some more divs inside-->
  </div>
 </div>
</div>

我想做的是仅将样式应用于第一个div.我尝试使用div:not(.abc, .abc *)div:not(.abc):not(.abc *)div:not(.abc), div:not(.abc) *,但是这些都不起作用.编辑html将非常困难,因为将有许多文件需要编辑.另外,上面显示的代码出现在不同的位置,因此使用>选择器不是解决方案...有人知道如何执行此操作吗?

What I want to do is to apply styles only to the first div. I tried to use div:not(.abc, .abc *), div:not(.abc):not(.abc *), div:not(.abc), div:not(.abc) * but none of these worked. It would be hard to edit the html, because there would be many files to be edited. Also the code shown above appears in different places, so using > selector is not the solution... Does someone know how to do this?

推荐答案

您不能在CSS中可靠地使用:not()选择器来排除元素和/或其后代. 此答案(及其链接的其他一些答案)中对此原因进行了解释:

You cannot reliably use the :not() selector in CSS for excluding an element and/or its descendants. The reason for it is explained in this answer (and some others that it links to):

您不能使用组合器.这适用于jQuery,但不适用于CSS:

You can't use combinators. This works in jQuery, but not CSS:

/* 
 * Grab everything that is neither #foo itself nor within #foo.
 * Notice the descendant combinator (the space) between #foo and *.
 */
:not(#foo, #foo *)

这个特别讨厌,主要是因为它没有适当的解决方法.有一些宽松的解决方法( 1

This one is particularly nasty, primarily because it has no proper workaround. There are some loose workarounds (1 and 2), but they usually depend on the HTML structure and are therefore very limited in utility.

并且由于您的标记难以预测,因此您无法对其进行编辑或使用>选择器,因此,除了找到一种将类应用于顶部的方法之外,恐怕没有太多的出路了div并使用该类,如Fluidbyte演示的 ,和/或使用jQuery,如上所述.

And since your markup is unpredictable enough that you cannot edit it or use the > selector, I'm afraid there's not much of a way out for you other than to either find a way to apply a class to your top div and use that class, as demonstrated by Fluidbyte, and/or use jQuery, as implied above.

这篇关于如何在样式定义中排除所有孩子的班级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆