Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the order of a class on a selector matter? If yes, can I specify the ordering?

Tags:

jquery

css

Is there a difference between:

<span id="test" class="one two"></span>

and

<span id="test" class="two one"></span>

If there are conflicting CSS rules on these classes does the order matter?

Are there any APIs in jQuery to reorder? When I call addClass() does it always go on the end?

like image 952
leora Avatar asked Dec 09 '11 00:12

leora


2 Answers

The order doesn't matter.

http://jsfiddle.net/rc8Yu/

css precedence

The important part here is

If two rules are equal in all of the above, the one declared last wins. CSS embedded in the html always come after external stylesheets regardless of the order in the html

like image 142
James Montagne Avatar answered Oct 17 '22 13:10

James Montagne


The order of the classes in HTML doesn't not matter, but the order inside the CSS does matter. For example, if you had:

span.one { color: red }
span.two { color: blue }

Both spans with class="one two" and class="two one" would produce blue text, because the class "two" is defined last. But if we changed that to

span.two { color: blue }
span.one { color: red }

and did the same thing, both spans would now have red text because the class "one" is defined last. Also keep in mind that the ID will override both of those classes no matter what, so if I defined:

span#test { color: green }

and added id="test", then the spans will always have green text no matter where in the document the classes and ID selector are defined, because an ID is naturally more specific than a class (other instances can make a class more specific than an ID, etc).


Since this is true, the order of your classes as assigned by jQuery is completely irrelevant. You should not need to worry about reordering them, but yes, addClass does just add the class to the end of the list.

like image 39
animuson Avatar answered Oct 17 '22 12:10

animuson