How to ignore css class

Is it possible to ignore css value?

I have two divs:

<div id="div1" class="class1 class2"> </div> <div id="div2" class="class1"> </div> 

Can the css class only apply to divs that have a style with class 1, and if they contain class2, then ignore it? So in the divs above, div2 has the style of class1, because div1 also has class 2.

+4
source share
6 answers

Write like this:

 .class1{ background:red; } .class1.class2{ background:none; } 
+7
source

You can use the :not selector. Here is an example:

CSS

 .red:not(.yellow) { color: red; } .yellow { background-color: yellow; } 

HTML:

 <div class = "red yellow"> Glee awesome! </div> <div class = "red"> Glee awesome! </div> 

Demo

I hope this helps!

+11
source

You can use the :not selector:

 $('.class1:not(.class2)') 
+2
source

YESSSS,

use! important after css property

e.g. height:30px !important

if your class1 has height:30px and class2 height:40px , then user! important in class2 height

+1
source

The way I would handle this with jquery (since you checked it, and if you only want a div with class class1 only), do a check like

 if($('div').class() == 'class1') { } 

This will select only the div where the class is equal to class1 , and not the one that has class class1 class2

0
source

Great answers here, and I just want to add a little here: You have to decide here between selectors that seem to do the same, but are slightly different:

  • "Override class1 styles if class2 present class2 " or "I want special styles when both classes are present."
  • "Apply custom styles if class1 present but class2 is not."
  • "I really want to suppress all class1 selector rules when class2 present."

You must decide what exactly your requirements are. There is a difference between these sentences.

In the first case, use CSS selectors such as @sandeep, because these selectors work like this. The .class1.class2 selector .class1.class2 more specific than the .class1 selector, and it is selected above it when both classes are present. Thus, you can set the rules there that you want to apply only if both classes are present. Collision rules in a more specific selector have a higher priority than others, and can override it.

In the second case, go to the selectors :not . They allow you to apply certain styles only when the class is present and the other is not.

In the third case: Your question indicates ignoring the css class. It's impossible. You can override your rules in a more specific selector or put your rules in a selector that does not match specific tags. But you cannot ignore him while he is not there. Therefore, you must remove class1 from the tag class attribute. You can achieve this with jQuery.

  $(".class2").removeClass("class1"); 
0
source

All Articles