我想编写一个CSS选择器规则来选择所有没有特定类的元素。例如,给定以下 HTML:
<html class="printable">
<body class="printable">
<h1 class="printable">Example</h1>
<nav>
<!-- Some menu links... -->
</nav>
<a href="javascript:void(0)" onclick="javascript:self.print()">Print me!</a>
<p class="printable">
This page is super interresting and you should print it!
</p>
</body>
</html>
我想编写一个选择器来选择所有没有“可打印”类的元素,在本例中,这些类是 nav 和 a 元素。
这可能吗?
注意:在我想使用它的实际 HTML 中,没有“可打印”类的元素会比没有(我意识到在上面的例子中是相反的)。
通常,您将类选择器添加到伪类中,如下所示::not()
:not(.printable) {
/* Styles */
}
:not([attribute]) {
/* Styles */
}
但是,如果您需要更好的浏览器支持(IE8及更早版本不支持),则最好为具有“可打印”类的元素创建样式规则。如果尽管您对实际标记进行了说明,但这仍然不可行,则可能必须围绕该限制进行标记。:not()
请记住,根据您在此规则中设置的属性,其中一些属性可能由 的后代继承,或者以某种方式影响它们。例如,虽然不是继承的,但设置 a 将阻止它及其所有后代显示,因为它会从布局中完全删除元素及其子树。您通常可以通过使用 instead 来解决此问题,这将允许显示可见的后代,但隐藏的元素仍将像最初一样影响布局。简而言之,要小心。.printable
display
display: none
:not(.printable)
visibility: hidden
:not([class])
实际上,这将选择任何没有应用css类()的内容。class="css-selector"
我做了一个jsfiddle演示
h2 {color:#fff}
:not([class]) {color:red;background-color:blue}
.fake-class {color:green}
<h2 class="fake-class">fake-class will be green</h2>
<h2 class="">empty class SHOULD be white</h2>
<h2>no class should be red</h2>
<h2 class="fake-clas2s">fake-class2 SHOULD be white</h2>
<h2 class="">empty class2 SHOULD be white</h2>
<h2>no class2 SHOULD be red</h2>
是否支持此功能?是 : Caniuse.com(02年2020月<>日访问):
有趣的编辑,我在谷歌上搜索:not.CSS否定的反面?
selector[class] /* the oposite of :not[]*/
:not
否定 CSS 伪类 ,是一种
函数表示法,采用简单的选择器 X 作为参数。它匹配参数未表示的元素
。X 不得包含另一个
否定选择器。:not(X)
您可以使用 排除匹配元素的任何子集,这些元素的顺序与普通 CSS 选择器一样。:not
div:not(.class)
将选择没有类的所有元素div
.class
div:not(.class) {
color: red;
}
<div>Make me red!</div>
<div class="class">...but not me...</div>
:not(div) > div
会选择所有不是另一个子元素的元素div
div
div {
color: black
}
:not(div) > div {
color: red;
}
<div>Make me red!</div>
<div>
<div>...but not me...</div>
</div>
除了无法链接/嵌套选择器和伪元素之外,您可以与其他伪选择器结合使用。:not
div {
color: black
}
:not(:nth-child(2)){
color: red;
}
<div>
<div>Make me red!</div>
<div>...but not me...</div>
</div>
:not
是一个CSS3级别选择器,在支持方面的主要例外是它是IE9+
该规范还提出了一个有趣的观点:
伪允许编写无用的选择器。例如
,它根本不表示任何元素,或者
,它等价于但具有更高的
特异性。:not()
:not(*|*)
foo:not(bar)
foo
模板简介:该模板名称为【HTML 编写一个 CSS 选择器来选择没有特定类或属性的元素吗?】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【HTML】栏目查找您需要的精美模板。