Combining two or more CSS selectors with a boolean condition

前端 未结 3 1283
情话喂你
情话喂你 2021-01-05 03:22

Is there a way to combine two or more CSS selectors using a boolean condition - and, or, not?

Consider this

<
相关标签:
3条回答
  • 2021-01-05 03:37

    This is a seriously old post, but I came across it and figured I'd add to it with the current CSS :not() selector:

    Select BOTH classes

    .message.error {}
    

    Select EITHER class

    .message, .error {}
    

    Select NEITHER class

    div:not(.message):not(.error) {}
    

    .message {
      border: 1px solid;
    }
    
    .error {
      color: red;
    }
    
    .message,
    .error {
      margin-bottom: 12px;
      padding: 12px;
    }
    
    .message.error {
      background: #ffcfcf;
    }
    
    div:not(.message):not(.error) {
      font: normal 20px "Comic Sans MS", cursive, sans-serif;
    }
    <div class="message">
        ONLY .message
    </div>
    
    <div class="error">
        ONLY .error
    </div>
    
    <div class="message error">
        BOTH classes
    </div>
    
    <div class="neither">
        NEITHER class
    </div>

    0 讨论(0)
  • 2021-01-05 03:47

    Try div.message.error.

    0 讨论(0)
  • 2021-01-05 03:48

    These should work:

    && = div.message.error {}
    || = div.message, div.error {}
    

    Don't think you can do "not"

    Edit: Just did a quick test to confirm:

    <html>
        <head>
            <style type="text/css">
                div.error.message {
                    background-color: red;
                }
                div.message, div.error {
                    border: 1px solid green;
                }
            </style>
        </head>
        <body>
            <div>None</div>
            <div class="error">Error</div>
            <div class="message">Message</div>
            <div class="error message">Error Message</div>
        </body>
    </html>
    

    The "message", "error" and "error message" divs all have a green border and only the "error message" div has a red background.

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