skip to Main Content

Is it possible to apply the CSS rule only if we detect that a div follows the rule?

Example

<div class="div1">...</div>
<div class="div2">..</div>

CSS Example

(if exist div2) .div2 .div1 (aply rule css to div1) {
    background-color: red;
}

3

Answers


  1. Chosen as BEST ANSWER

    I found the solution:

    div1:has(+ div2) {
        background-color: pink;
    }
    

  2. You can use the has() pseudo-class in combination with the next sibling
    selector
    :

    .div1:has(+ .div2) {
      background: red;
    }
    <div class="div1">...</div>
    <div class="div2">...</div>
    Login or Signup to reply.
  3. In this example, the CSS rule .div2 + .div1 targets a .div1 that directly follows a .div2.

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <style>
            /* Your default styles for .div1 */
            .div1 {
                background-color: blue;
            }
    
            /* Additional styles for .div1 when it follows .div2 */
            .div2 + .div1 {
                background-color: red;
            }
        </style>
    </head>
    <body>
    
        <div class="div1">This is div1</div>
        <div class="div2">This is div2</div>
        <div class="div1">This is another div1</div>
    
    </body>
    </html>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search