我想使用 :not
伪类作为异常(exception),其中 css 应适用于除具有特定类的任何元素(包括其所有子元素)之外的所有元素。
但在我的示例中,:not
选择器影响一切,但只应影响 :not
内的类选择器。我正在使用 Chrome 浏览器。
SCSS:
.ql-editor :not(.not-ql-editor){
ul > li {
background:blue;
}
}
HTML:
<div class="ql-editor">
<ul>
<li>hello</li>
<li>hello</li>
<li>hello</li>
</ul>
<div class="not-ql-editor">
<ul>
<li>hello</li>
<li>hello</li>
<li>hello</li>
</ul>
</div>
</div>
我本来期望顶部 <ul><li>
有蓝色背景,而较低的<ul><li>
不会有背景,因为它有 .not-ql-editor
类,但由于没有 li
似乎有些不对劲元素获取背景。
更新:
在约翰内斯的回答之后,我了解到上层 ul
需要包裹在一些元素内,因为 :not(.not-ql-editor)
表示一个元素,即使它与选择器不匹配。
但后来我注意到 "not-ql-editor
"元素必须直接位于 "ql-editor"
元素的下方。我的目标是针对位于 "ql-editor
下方任何级别的类".
通常,当您在两个选择器之间放置一个空格时,第二个选择器应该定位第一个选择器下方任何级别的元素。 :not 选择器不是这种情况吗?
更新2:
这是 fiddle 的修改版本: fiddle2
如果 html 看起来像这样(具有相同的 css):
<div class="ql-editor">
<div>
<div class="not-ql-editor">
<ul>
<li>hello</li>
<li>hello</li>
<li>hello</li>
</ul>
</div>
</div>
</div>
李变成蓝色。尽管有 css:.ql-editor :not(.not-ql-editor)
最佳答案
您的代码中的问题是第一个列表与第二个列表处于不同的“后代级别”:您的 CSS 选择器仅对 ul
中的 li
元素有效code> 是没有 .not-ql-editor
的元素的 child 又是具有 .ql-editor 的元素的子元素
类。
为此,您需要另一个 div
(或其他)包装您的第一个 ul
:
.ql-editor :not(.not-ql-editor) ul>li {
background: blue;
}
<div class="ql-editor">
<div>
<ul>
<li>hello></li>
<li>hello</li>
<li>hello</li>
</ul>
</div>
<div class="not-ql-editor">
<ul>
<li>hello</li>
<li>hello</li>
<li>hello</li>
</ul>
</div>
</div>
评论和问题编辑后的添加:
在您发布的第一个代码示例中,您的 ul
元素与 .ql-editor
DIV 元素处于不同的后代级别:第一个 ul
是直子,第二个是孙子,.not-ql-editor
DIV 作为 .ql-editor
和 ul< 之间的包装器
。我的回答是针对这种情况的,而且有效。
在您发布的第二个代码示例中,您添加了另一个级别:.ql-editor
DIV 和 .not-ql-editor
之间没有任何类的 DIV > 分区。这改变了事情。在您添加的 fiddle 中,.not-ql-editor
DIV 是 ul
的直接父级。因此,您需要使用 that 关系来定义一个 CSS 规则,该规则仅在 ul
是 direct 的 DIV 子级时才适用>没有 .not-ql-editor
类。
在纯 CSS 中,规则如下:
.ql-editor *:not(.not-ql-editor) > ul > li {
background: blue;
}
这是您的第二个代码示例,在片段中结合了该 CSS 规则,背景*不会*变成蓝色:
.ql-editor *:not(.not-ql-editor) > ul > li {
background: blue;
}
<div class="ql-editor">
<div>
<div class="not-ql-editor">
<ul>
<li>hello</li>
<li>hello</li>
<li>hello</li>
</ul>
</div>
</div>
</div>
这是您将此 CSS 应用为 SCSS 的第二个 fiddle :https://jsfiddle.net/e7d0h4yc/
关于CSS :not pseudo class is not taking effect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58218322/