622

Is there a way to select an element with CSS based on the value of the class attribute being set to two specific classes. For example, let's say I have 3 divs:

<div class="foo">Hello Foo</div>
<div class="foo bar">Hello World</div>
<div class="bar">Hello Bar</div>

What CSS could I write to select ONLY the second element in the list, based on the fact that it is a member of both the foo AND bar classes?

3 Answers 3

976

Chain both class selectors (without a space in between):

.foo.bar {
  /* Styles for element(s) with foo AND bar classes */
}

If you still have to deal with ancient browsers like Internet Explorer 6, be aware that it doesn't read chained class selectors correctly: it'll only read the last class selector (.bar in this case) instead, regardless of what other classes you list.

To illustrate how other browsers and IE6 interpret this, consider this snippet:

* {
  color: black;
}

.foo.bar {
  color: red;
}
<div class="foo">1. Hello Foo</div>
<div class="foo bar">2. Hello World</div>
<div class="bar">3. Hello Bar</div>

The page will look like this:

  • On supported browsers:

    1. Not selected as this element only has class foo.
    2. Selected as this element has both classes foo and bar.
    3. Not selected as this element only has class bar.
  • In Internet Explorer 6:

    1. Not selected as this element doesn't have class bar.
    2. Selected as this element has class bar, regardless of any other classes listed.
    3. Selected as this element has class bar.
7
  • 7
    Does it matter the order I put them in?
    – Adam
    Sep 22, 2010 at 18:08
  • 5
    It doesn't matter. (It will for IE6 because of how it interprets it, assuming you must support it.)
    – BoltClock
    Sep 22, 2010 at 18:09
  • 8
    Does it matter that there's no space between them? Mar 3, 2015 at 22:25
  • 34
    @Imray: Yes, the space represents a descendant selector, which would make each class selector represent a different element. But we're talking about a single element here.
    – BoltClock
    Mar 4, 2015 at 3:11
  • 4
    Works for classes and id's in any order: .tab_active#tab1 and #tab1.tab_active Jan 23, 2021 at 0:12
7

With SASS:

.foo {
  /* Styles with class "foo" */

  &.bar {
    /* Styles with class "foo bar" */
  }
}

See What is the meaning of an ampersand in Less selectors?

0
1

It can be done by two ways in SCSS.

Option 1

.foo.bar {
    // Styles with class "foo bar"
}

Option 2

.foo {
   &.bar {
        // Styles with class "foo bar"
    }
 }

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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