Tutorial :css stylesheet stronger than jquery addClass?


Hey guys this thing drives me crazy. I defined in my stylesheet:

ul#menuCnt li a {     color:"red";  }  

If I want to make a hover effect, using jquery this won't change any color.

$("ul#menuCnt li a").hover(function() {          $(this).addClass("brown");      }, function() {          $(this).removeClass("brown");      });  

I am really confused. If I don't define a color in my css stylesheet the hovereffect works.

Hope you can help me. You guys helped me so much by learning jquery and css :)

Thank you!


According to css priorities, if your class .brown is defined like this in your css file :


The rules inside will not override same rules in your # selector.

You can make it override them using the !important keyword.

.brown {      color: brown !important;  }  

Altough this is not the best solution here, it will work... The less you use !important, the more your code will be easy to read.

See http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html.


Do you have a .brown selector in your CSS? Also an a tag might be a bad choice because it has a very good :hover selector build in.


I don't see you mention a issue with using css to do this, so why not try:

ul#menuCnt li a:hover {     color:"brown";  }  

Edit: It should actually work in ie6, seeing as it is an anchor :) It would be much faster than using javascript to do it.


You have a very specific element specifier here. That's considered more important than a simple .brown class selector, and thus it doesn't have much effect.

See for example this site for more info


Why don't you use the CSS :hover pseudoclass? For example:

#menuCnt li a {      color: "red";  }    #menuCnt li a:hover {      color: "brown";  }  

Also, the usage of "UL" in the selector shouldn't be necessary. There's no way that there are other elements on the page with the ID "menuCnt" as the ID attribute must be unique in the DOM.


I did some testing with IE/FF and discovered that including the element's ID in your stylesheet (ul#menuCnt) prevents JQuery from overriding that style - at least with the methods I employed (toggleClass, addClass, removeClass, etc.).

If you assign the class to the element in the tag (instead of specifying the ID in the stylesheet) you can override it with JQuery.

If you remove the ID from the style you can override it with JQuery (not really useful but good for demonstrating behavior).

In fact, if you leave the ID in your stylesheet and attempt to assign a different class within the tag, you still see the class associated with the ID in the stylesheet.

NOTE: Vincent's post suggests why we see this behavior.

I also agree with exhuma's suggestion to use :hover in your CSS.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »