选择不含有特定类/属性/类型的元素的 CSS 选择器
使用 CSS :not() 伪类,我们可以通过选择没有特定值或不匹配选择器的元素来优化我们的样式。
选择没有子选择器的元素
要选择没有子选择器的元素,请在 CSS 中使用 :not 伪类。
此处,我们有一个子选择器。CSS 子选择器用于选择具有特定父元素的所有子元素。它选择所有作为 <div> 子元素的 <p> 元素,即。
div>p
但是我们选择的是没有此 div>p −
p:not(div>p) {
background-color: orange;
font-size: 1.4em;
font-style: italic;
color: blue;
}
示例
以下示例说明了 CSS :not 伪类 −
<!DOCTYPE html>
<html>
<head>
<style>
p {
background-color: cornflowerblue;
color: white;
}
p:not(div>p) {
background-color: orange;
font-size: 1.4em;
font-style: italic;
color: blue;
}
</style>
</head>
<body>
<div>
<p>Curabitur sapien diam, imperdiet ut est sed, blandit blandit velit. Nunc viverra nunc id ligula ultricies, a fringilla lacus interdum. <span>Sed vel diam at magna pellentesque porttitor.</span></p>
<h3>Demo</h3>
</div>
<p>This is a demo text.</p>
</body>
</html>
选择不含有某个类型的元素
我们将使用 :not 选择器选择不含有某个类型,如下所示 −
div:not(.parent) {
box-shadow: inset 0 0 24px tomato;
padding: 2%;
}
在上面,我们有以下父类 −
<div class="parent">
<div class="one">
<div class="two"></div>
<div class="two"></div>
</div>
<div class="one"></div>
</div>
示例
让我们来看一个选择不含有某个类型的元素的示例 −
<!DOCTYPE html>
<html>
<head>
<style>
div {
margin: 2%;
background-color: cadetblue;
padding: 10%;
height: 80px;
}
div:not(.parent) {
box-shadow: inset 0 0 24px blue;
padding: 2%;
}
.parent{
border: 8px ridge orange;
color: white;
}
.one {
background-color: lightgreen;
border: 4px groove gray;
}
.two{
height: 20px;
}
</style>
</head>
<body>
<div class="parent">Parent div
<div class="one">
<div class="two"></div>
<div class="two"></div>
</div>
<div class="one"></div>
</div>
</body>
</html>
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP