Home > Web Front-end > CSS Tutorial > How to Exclude Specific Class Names in CSS Selectors?

How to Exclude Specific Class Names in CSS Selectors?

Mary-Kate Olsen
Release: 2024-11-04 22:29:01
Original
1019 people have browsed it

How to Exclude Specific Class Names in CSS Selectors?

Excluding Specific Class Names in CSS Selectors

In CSS, there are instances where you may need to exclude particular class names from your selectors. This is especially useful when you want to apply styles to multiple elements, but certain ones should not inherit those styles.

One common scenario involves excluding elements with a specific class name while applying styles to elements with another class name. Let's consider the following example:

<code class="html"><a href="" title="Design" class="reMode_design reMode_hover">
    <span>Design</span>
</a>

<a href="" title="Design" class="reMode_design reMode_hover reMode_selected">
    <span>Design</span>
</a></code>
Copy after login

In this example, we want to apply a background color to elements with the "reMode_hover" class name on hover. However, we do not want to apply this color if the element also has the "reMode_selected" class name.

<code class="css">/* Do not apply background-color (leave empty) */
.reMode_selected .reMode_hover:hover { }

.reMode_hover:hover { background-color: #f0ac00; }</code>
Copy after login

While you might expect the first rule to work, it does not. This is because in CSS, space between class names denotes the descendant selector. So, ".reMode_selected .reMode_hover" translates to "select .reMode_hover elements that are descendants of .reMode_selected."

To exclude "reMode_selected" elements correctly, we need to use the "not()" selector. The updated CSS would be:

<code class="css">.reMode_hover:not(.reMode_selected):hover { background-color: #f0ac00; }</code>
Copy after login

This rule will apply the background color to .reMode_hover elements that do not have the .reMode_selected class name. As a result, only the first link will receive the background color on hover, while the second link will not.

The above is the detailed content of How to Exclude Specific Class Names in CSS Selectors?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template