How to exclude a specific class name in CSS selector?

I am trying to apply a background color when a user mouse moves over an element whose class name is "reMode_hover" .

But I do not want to change the color if the element also has "reMode_selected"

Note. I can use non-javascript CSS because I work in some limited environment.

To clarify, my goal is to colorize the first element on hover, but not the second element.

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> 

I tried below, hoping that the first definition will work, but it is not. What am I doing wrong?

CSS

 /* do not apply background-color so leave this empty */ .reMode_selected .reMode_hover:hover { } .reMode_hover:hover { background-color: #f0ac00; } 
+72
html css css-selectors
Apr 24 '13 at 20:52
source share
3 answers

One way is to use a selector of several classes (without a space, which is a descendant selector):

 .reMode_selected.reMode_hover:hover { background-color: transparent; } 

http://jsfiddle.net/geatR/

Another option is to use a selector :not()

 .reMode_hover:not(.reMode_selected):hover { background-color: #f0ac00; } 

http://jsfiddle.net/geatR/1/

+136
Apr 24 '13 at
source share

In modern browsers you can:

 .reMode_hover:not(.reMode_selected):hover{} 

See http://caniuse.com/css-sel3 for compatibility information.

+19
Apr 24 '13 at
source share

Method 1

The problem with your code is that you select .remode_hover , which is a descendant of .remode_selected . So, the first part of your code to work correctly is to remove this space.

 .reMode_selected.reMode_hover:hover 

Then, so that the style does not work, you must override the style set by :hover . In other words, you need to contrast the background-color property. So the final code will be

 .reMode_selected.reMode_hover:hover { background-color:inherit; } .reMode_hover:hover { background-color: #f0ac00; } 

Fiddle

Method 2

An alternative method would be to use :not() as indicated by others. This will return any element that does not have the class or property specified in parentheses. In this case, you put .remode_selected there. This will target all elements that do not have a class .remode_selected

Fiddle

However, I would not recommend this method because it was introduced in CSS3, so browser support is not perfect.

Method 3

The third method is to use jQuery. You can target the .not() selector, which will be similar to using :not() in CSS, but with much better browser support

Fiddle

+8
Apr 24 '13 at
source share



All Articles