413

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 class="left ui-class-selector">

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

Ivar
  • 5,377
  • 12
  • 50
  • 56
Ciel
  • 16,854
  • 20
  • 103
  • 198

3 Answers3

674

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?

Community
  • 1
  • 1
Felix Kling
  • 756,363
  • 169
  • 1,062
  • 1,111
  • 6
    Please note that IE6 does not like these, as it does not read the chain of classes. It will only look at the last class in the chain. – akamike Mar 31 '10 at 16:55
  • 18
    it isn't :) All major websites have dropped, are dropping or are planning to drop in the near future support for IE6.. Do the same! – Thomas Bonini Mar 31 '10 at 16:58
  • @Andreas Bonini: Yeah I know. To be honest I already don't care about IE6 for a long time. (I deleted my previous comment because I found the other question that deals with this problem.) – Felix Kling Mar 31 '10 at 17:01
  • Yeah, you can't use them at all in IE6, only take longer routes to style your elements. For example, styling each class separately and using appropriate CSS specificity to override as best as you can. – akamike Mar 31 '10 at 17:07
  • 3
    I fondly remember dancing on the grave of IE6. I haven't even had to support IE10 this year, and dropping IE altogether is on the horizon. I love the future. ☺ – Michael Scheper Jun 28 '18 at 00:42
28

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*/
}
nidhi0806
  • 293
  • 3
  • 13
0

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";
bahman parsamanesh
  • 2,194
  • 3
  • 13
  • 31