how do I select a div with class “A” but NOT with class “B”?

前端 未结 3 1025
悲&欢浪女
悲&欢浪女 2021-02-06 20:14

I have some divs:

\"Target\"
\"NotMyTarget\"
\"NotMyTarget\"<
相关标签:
3条回答
  • 2021-02-06 20:40
    .A:not(.B) {}
    

    But guess who doesn't support that... Indeed, IE<=8.

    0 讨论(0)
  • 2021-02-06 20:43

    I think the best you can do (until CSS 3) is override the styles in this case with what you don't want from class A B in A, like this:

    .A.B { /* Styles */ }
    .A { /* Reverse any styling you don't want */ }
    
    0 讨论(0)
  • 2021-02-06 20:47

    You can use the attribute selector to match the div that has only one class:

    div[class=A] {
      background: 1px solid #0f0;
    }
    

    If you want to select another div that has multiple classes, use quotes:

    div[class="A C"] {
      background: 1px solid #00f;
    }
    

    Some browsers do not support the attribute selector syntax. As usual, "some browsers" is a euphemism for IE 6 and older.

    See also: http://www.quirksmode.org/css/selector_attribute.html

    Full example:

    <!DOCTYPE html>
    <html>
    <head>
      <style>
        .A { font-size:22px; }
        .B { font-weight: bold; border: 1px solid blue; }
        .C { color: green; }
    
        div[class="A"] {
          border: 1px solid red;
        }
        div[class="A B"] {
          border: 3px solid green;
        }
      </style>
    </head>
    <body>
      <div class="A">"Target"</div> 
      <div class="A B">"NotMyTarget"</div> 
      <div class="A C">"NotMyTarget"</div> 
      <div class="A D">"NotMyTarget"</div> 
      <div class="A E">"NotMyTarget"</div> 
    </body>
    </html>
    

    EDIT 2014-02-21: Four years later, :not is now widely available, though verbose in this specific case:

    .A:not(.B):not(.C):not(.D):not(.E) {
      border: 1px solid red;
    }
    

    Unfortunately, this doesn't work in IE 7–8 as specified in the question: http://caniuse.com/#search=:not

    0 讨论(0)
提交回复
热议问题