Home >Web Front-end >CSS Tutorial >How to Exclude Specific Classes from CSS Selectors: A Step-by-Step Guide

How to Exclude Specific Classes from CSS Selectors: A Step-by-Step Guide

Linda Hamilton
Linda HamiltonOriginal
2024-11-05 01:39:02513browse

How to Exclude Specific Classes from CSS Selectors: A Step-by-Step Guide

Excluding Specific Class from CSS Selector

When targeting elements with multiple classes, it becomes crucial to accurately select or exclude specific classes to achieve desired styling. This article addresses a common scenario where you need to apply a background color to elements with a particular class but exclude those that also have another specific class.

Example Scenario

Consider the following HTML markup:

<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>

The goal is to apply a background color to the first link when the user hovers over it, but exclude the second link from this effect because it has the additional class "reMode_selected."

Initial Attempt

You may initially try the following CSS:

<code class="css">.reMode_selected .reMode_hover:hover {}

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

However, this won't work correctly because the first rule overrides the second rule. To correctly exclude the elements with the "reMode_selected" class, use the multiple class selector:

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

This rule targets elements with the "reMode_hover" class but excludes those that also have the "reMode_selected" class when they are hovered over. As a result, the first link will receive the background color on hover, while the second link will remain unchanged.

The above is the detailed content of How to Exclude Specific Classes from CSS Selectors: A Step-by-Step Guide. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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