CSS Selector that applies to elements with two classes

前端 未结 1 1793
猫巷女王i
猫巷女王i 2020-11-22 05:42

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:



        
相关标签:
1条回答
  • 2020-11-22 06:30

    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 IE6, 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 CSS:

    * {
        color: black;
    }
    
    .foo.bar {
        color: red;
    }
    

    Output on supported browsers is:

    <div class="foo">Hello Foo</div>       <!-- Not selected, black text [1] -->
    <div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
    <div class="bar">Hello Bar</div>       <!-- Not selected, black text [3] -->
    

    Output on IE6 is:

    <div class="foo">Hello Foo</div>       <!-- Not selected, black text [1] -->
    <div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
    <div class="bar">Hello Bar</div>       <!-- Selected, red text [2] -->
    

    Footnotes:

    • 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.

    • IE6:
      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.
    0 讨论(0)
提交回复
热议问题