447

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.

1

3 Answers 3

720

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?

4
  • 7
    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
    Commented Mar 31, 2010 at 16:55
  • 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
    Commented Mar 31, 2010 at 17:07
  • 1
    what happens if there IS a space between class selectors?
    – BenKoshy
    Commented Aug 3, 2022 at 2:41
  • 2
    @BenKoshy: It's interpreted as the descendant combinator. .a .b applies to all elements .b that have an element .a as their ancestor. Commented Aug 3, 2022 at 8:03
33

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
  • 19
    Id & Id is a conceptually strange selector. Commented Aug 10, 2018 at 14:23
  • 6
    The double ID selector is impossible I would think because it says you need to have two different IDs for the same element.
    – Jowe
    Commented Oct 27, 2020 at 2:46
5

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";

Not the answer you're looking for? Browse other questions tagged or ask your own question.