Why doesn#39;t this CSS :not() declaration filter down?(为什么这个 CSS :not() 声明不过滤掉?)
问题描述
我想选择不是特定类的后代的跨度,我们称之为否".这是我的 CSS:
div:not(.no) span{background-color:#00f;}这是 HTML
<div><span>是 1</span></div><div 类="否"><span>没有 1</span></div><div 类="否"><span>没有 2</span></div></div>两个问题:
- 为什么我的 CSS 同时适用于 yes 1 和 no 2?
如果我切换到通用选择器,为什么整个事情都会中断?
*:not(.no) span{background-color:#00f;}
这是 JSFiddle 中的代码:http://jsfiddle.net/stephaniehobson/JtNZm/
解决方案 两个 span 元素的父 div 元素都没有类 no,无论是否有其他祖先有没有:
<div><!-- 这是 div:not(.no),几乎是给定的 --><span>是 1</span></div>
<div class="no"><!-- 在这种情况下,虽然这是 div.no... --><!-- ... 这是 div:not(.no)!--><span>没有 2</span></div></div>作为 div 和 span 元素的祖先的 html 和 body 都满足*:not(.no) 当使用通用选择器时(或者更确切地说,当省略类型选择器时).这会导致 所有 您的 span 元素具有背景颜色.
一个解决方案是使用子组合器将否定过滤器锚定到 body 元素,如果您的顶级 div 元素始终是 的子元素>正文:
body >div:not(.no) span { 背景颜色:#00f;}
jsFiddle 演示
另一种解决方案是简单地使用覆盖样式.
I want to select spans that are not the descendants of a specific class, let's call it "no". Here's my CSS:
div:not(.no) span{background-color:#00f;}
Here's the HTML
<div>
<span>yes 1</span>
</div>
<div class="no">
<span>no 1</span>
</div>
<div class="no">
<div>
<span>no 2</span>
</div>
</div>
Two questions:
- Why does my CSS apply to both yes 1 and no 2?
Why does the whole thing break if I switch to a universal selector?
*:not(.no) span{background-color:#00f;}
Here's the code in JSFiddle: http://jsfiddle.net/stephaniehobson/JtNZm/
解决方案
Both of the span elements' parent div elements don't have the class no, regardless of whether any other ancestors do have it or not:
<div> <!-- This is div:not(.no), pretty much a given -->
<span>yes 1</span>
</div>
<div class="no"> <!-- In this case, although this is div.no... -->
<div> <!-- ... this is div:not(.no)! -->
<span>no 2</span>
</div>
</div>
Both html and body, which are ancestors of your div and span elements, satisfy *:not(.no) when using a universal selector (or rather, when omitting a type selector). This causes all of your span elements to have the background color.
One solution to this is to anchor your negation filter to the body element using the child combinator, if your top-level div elements will always be children of body:
body > div:not(.no) span { background-color: #00f; }
jsFiddle demo
Another solution is to simply use override styles.
这篇关于为什么这个 CSS :not() 声明不过滤掉?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么这个 CSS :not() 声明不过滤掉?
基础教程推荐
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
