Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Role of CSS :not (selector) Selector
The CSS :not() selector is used to select and style every element that does not match the specified selector. This pseudo-class selector allows you to apply styles to all elements except those that match a particular criterion, making it useful for creating exclusion-based styling rules.
Syntax
:not(selector) {
property: value;
}
Example: Basic :not() Selector
The following example demonstrates how to style all elements except paragraphs −
<!DOCTYPE html>
<html>
<head>
<style>
p {
color: red;
}
:not(p) {
color: blue;
}
</style>
</head>
<body>
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<h3>Heading 3</h3>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>
Heading 1, Heading 2, and Heading 3 appear in blue color, while both paragraphs appear in red color.
Example: :not() with Class Selector
You can also use the :not() selector with class selectors to exclude elements with specific classes −
<!DOCTYPE html>
<html>
<head>
<style>
div {
padding: 10px;
margin: 5px;
border: 1px solid #ccc;
}
div:not(.highlight) {
background-color: #f0f0f0;
}
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<div>Regular div</div>
<div class="highlight">Highlighted div</div>
<div>Another regular div</div>
</body>
</html>
Three div elements appear with borders and padding. The first and third divs have a light gray background, while the middle div with the "highlight" class has a yellow background.
Conclusion
The :not() selector is a powerful tool for applying styles to all elements except those matching a specific selector. It's particularly useful for creating general styling rules while making exceptions for certain elements or classes.
