0

My markup contains a tree structure of same element that looks something like this:

<div class="node">
  <div class="node">
    <div class="node" />
  </div>
  <div class="node" />
</div>

What I would like to do is to alternate their background colors for each depth. I was able to achieve this by pretty ugly css and was wondering if there is a smarter way. Here is the naive solution:

.a {
  height: 10px;
  background-color: red;
  .a {
    background-color: green;
    .a {
      background-color: red;
      /* etc... */
    }
  }
}
10
  • If you're auto-generating this using some script, then you could track it using an iterator variable, like for(let i = 0; i < .... Otherwise, you could just add a class to each child like odd and even. Commented Mar 28, 2019 at 18:01
  • It's a React app and the nodes are components (more or less) but it wouldn't be that simple to carry over the information whether current node should be odd or even in script. Commented Mar 28, 2019 at 18:08
  • Do you know the maximum depth before hand? Is it always 3? Commented Mar 28, 2019 at 18:15
  • @AskYous yes that seems to be pretty similar, so it seems that this can't be done with css purely. Commented Mar 28, 2019 at 18:17
  • Yeah you can't. If you know the maximum depth, you can write it easily using LESS or SASS, assuming it's not that big. Otherwise, you could write code to generate a new style tag. Commented Mar 28, 2019 at 18:18

1 Answer 1

0

Use the direct descendent selector

// Parent
.a {
  background: red;
}

// Child
.a > .a {
  background: green;
}

// Grandchild
.a > .a > .a {
  background: red;
}

.a {
  height: 50px;
  padding: 10px;
  width: 100%;
}

.a {
  background: red;
}

.a > .a {
  background: green;
  height: 30px;
  width: 100%;
}

.a > .a > .a {
  background: red;
  height: 10px;
  width: 100%;
}
<div class="a">
  <div class="a">
    <div class="a"></div>
    <div class="a"></div>
</div>

Sign up to request clarification or add additional context in comments.

3 Comments

That's exactly what I'm already doing.
Are you trying to do it more dynamically?
Yes because the depth is not limited.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.