Home > OS >  How to apply style on first child of multilevel recursive classes
How to apply style on first child of multilevel recursive classes

Time:01-11

Im trying to apply a style only on the first grand child of the main container. The structure looks like this.

.container {
  display: flex;
}

.container.main {
  border: 1px solid gray;
}

.container.main .item>* {
  border-color: red;
}

.item {
  width: 30px;
  height: 30px;
  border: 1px solid blue;
  margin: 1px 1px 2px;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="style.css">
  <title>Document</title>
</head>

<body>
  <div >
    <div >
      <div ></div>
      <div >
        <div >

        </div>
        <div >
          <div >
            <div >
              <div ></div>
              <div ></div>
              <div ></div>
              <div >
                <div ></div>
                <div ></div>

              </div>
            </div>
          </div>
          <div ></div>
        </div>
      </div>
    </div>
  </div>
</body>

</html>

I want the first child to be yellow and the last child to be dotted. How can I do this? As you can see each child could be some level deep in different container.

CodePudding user response:

There's no way to do this with only CSS due to the differing levels. However, using a combination of CSS and javascript:

.item.first { /* some style */ }
.item.last { /* some other style */ }
const root = document.querySelector('.container.main');
const items = root.querySelectorAll('.item');
items[0].classList.add('first');
items[items.length-1].classList.add('last');
  •  Tags:  
  • Related