I have a style rule I want to apply to a tag when it has two classes. Is there any way to perform this without JavaScript? In other words:

<li> 

I want to apply my style rule only if the li has both .left and .ui-class-selector classes applied.

1

3 Answers

You mean two classes? "Chain" the selectors (no spaces between them):

.class1.class2 { /* style here */ } 

This selects all elements with class1 that also have class2.

In your case:

li.left.ui-class-selector { } 

Official documentation : CSS2 class selectors.


As akamike points out a problem with this method in Internet Explorer 6 you might want to read this: Use double classes in IE6 CSS?

5

Chain selectors are not limited just to classes, you can do it for both classes and ids.

Classes

.classA.classB { /*style here*/ } 

Class & Id

.classA#idB { /*style here*/ } 

Id & Id

#idA#idB { /*style here*/ } 

All good current browsers support this except IE 6, it selects based on the last selector in the list. So ".classA.classB" will select based on just ".classB".

For your case

li.left.ui-class-selector { /*style here*/ } 

or

.left.ui-class-selector { /*style here*/ } 
2

You can use these solutions :

CSS rules applies to all tags that have following two classes :

.left.ui-class-selector { /*style here*/ } 

CSS rules applies to all tags that have <li> with following two classes :

li.left.ui-class-selector { /*style here*/ } 

jQuery solution :

$("li.left.ui-class-selector").css("color", "red"); 

Javascript solution :

document.querySelector("li.left.ui-class-selector").style.color = "red"; 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy