Is CSS stylesheet stronger than jquery addClass?

Hey guys, this thing is driving me crazy. I have defined in my stylesheet:

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

      

If I want to create a hover effect using jquery will not change the 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.

I hope you can help me. You guys helped me a lot by learning jquery and css :)

Thank!

+2


source to share


6 answers


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

.brown{}

      

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

You can override them with a keyword !important

.



.brown {
    color: brown !important;
}

      

While not the best solution here, it will work ... The less you use, the more your code will be easier to read.

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

+10


source


Do you have a selector .brown

in your CSS? Also a tag a

can be a bad choice because it has a very good selector :hover

.



+2


source


I don't see you mentioning the problem of using css for this, so why not try:

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

      

Edit: it should work in ie6, seeing that it is an anchor :) It will be much faster than using javascript to do this.

+2


source


You have a very specific element specifier here. This is considered more important than the simple "class" selector, and therefore has little effect.

See, for example, this site for more information

+2


source


Why don't you use a CSS pseudoslot :hover

? For example:

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

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

      

Also, the use of "UL" in the selector is optional. There is no way for the page to have other elements with the ID "menuCnt", since the ID attribute must be unique in the DOM.

+1


source


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

If you are assigning a class to an element in a tag (instead of specifying an id in your stylesheet), you can override it with JQuery.

If you remove the id from the style, you can override it with jQuery (not very useful, but useful for demonstrating behavior).

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

Note: Vincent's post suggests why we are seeing this behavior.

I also agree with exgum's suggestion to use: hover over your CSS.

0


source







All Articles