The :not()
pseudo-class in CSS is a functional pseudo-class that takes a selector list as an argument. It matches elements that are not represented by the selectors in the argument. This is extremely useful for excluding specific elements from a broader set of selected elements, leading to more concise and readable CSS.
Example 1: Basic Exclusion
/* Selects all <p> elements that are not the one with the ID 'special' */
p:not(#special) {
color: blue;
}
Explanation
This code selects all paragraph (<p>
) elements on the page except for the one that has the id="special"
. This allows you to apply a general style to most paragraphs while easily making an exception for a specific one.
Example 2: Excluding a Class
/* Selects all <div> elements that do not have the class 'exempt' */
div:not(.exempt) {
border: 1px solid black;
}
Explanation
Here, all <div>
elements will receive a solid black border, unless they have the class exempt
. This is a common way to prevent certain elements from receiving a widespread style.
Example 3: Excluding an Attribute
/* Selects all <a> elements that do not have an href attribute starting with 'https://' */
a:not([href^="https://"]) {
color: orange;
}
Explanation
This example targets anchor <a>
tags. It changes the color to orange for any <a>
tag whose href
attribute does not begin with https://
. This can be useful for styling internal or non-secure links differently.
Example 4: Excluding the First Child
/* Selects all list items except the first one */
li:not(:first-child) {
margin-top: 10px;
}
Explanation
This CSS rule applies a top margin to every list item (<li>
) except for the very first one in a list. This is useful for adding space between list items without adding unnecessary space before the first item.
Example 5: Excluding Multiple Selectors
/* Selects all <input> elements that are not hidden or disabled */
input:not([type="hidden"]):not([disabled]) {
padding: 8px;
}
Explanation
You can chain :not()
pseudo-classes. This code selects all <input>
elements that are neither of type="hidden"
nor have the disabled
attribute. This is great for applying styles only to interactive input fields.
Example 6: Excluding Descendants
/* Selects all <p> elements that are not inside an <article> element */
body :not(article) > p {
font-style: italic;
}
Explanation
This selector targets <p>
elements that are direct children of any element that is not an <article>
. This allows for styling paragraphs differently based on their parent container.
Example 7: Complex Selector Negation
/* Selects elements that are not a <header> or <footer> with the class 'site-section' */
:not(header.site-section, footer.site-section) {
background-color: #f0f0f0;
}
Explanation
This example demonstrates excluding elements that match a more complex selector. It applies a background color to every element except for <header>
and <footer>
elements that also have the class site-section
.