skip to Main Content

I recently discovered the :has() pseudo-class. When I tried to test it I didn’t see any changes. I really don’t know why.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  height: 100vh;
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
}

section {
  background-color: hotpink;
  width: 500px;
  height: 500px;
  margin: 10px;
}

section:has(div) {
  background-color: blueviolet;
}
<section>
  <h1></h1>
</section>
<section></section>
<section></section>
<section></section>

2

Answers


  1. None of the sections in your code has a div inside it.

    This snippet changes the background if it has an h1.

    [Note as at time of posting this, Firefox does not support :has by default, the user has to change a setting].

    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    
    body {
      height: 100vh;
      display: flex;
      justify-content: space-around;
      flex-wrap: wrap;
    }
    
    section {
      background-color: hotpink;
      width: 500px;
      height: 500px;
      margin: 10px;
    }
    
    section:has(h1) {
      background-color: blueviolet;
    }
    <!DOCTYPE html>
    <html>
    
    <head>
      <link rel="stylesheet" href="style.css">
    </head>
    
    <body>
      <section>
        <h1></h1>
      </section>
      <section></section>
      <section></section>
      <section></section>
    </body>
    
    </html>
    Login or Signup to reply.
  2. Here is the working example:
    section:has(div) checks if there is any div inside the section exists then it will apply the stylings

    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    
    body {
      height: 100vh;
      display: flex;
      justify-content: space-around;
      flex-wrap: wrap;
    }
    
    section {
      background-color: hotpink;
      width: 500px;
      height: 500px;
      margin: 10px;
    }
    
    section:has(div) {
      background-color: blueviolet;
    }
    <!DOCTYPE html>
    <html>
    <head>
      <link rel="stylesheet" href="style.css">
    </head>
    
    <body>
      <section>
        <div></div>
      </section>
      <section></section>
      <section></section>
      <section></section>
    </body>
    
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search