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... */
    }
  }
}
Maroš Beťko
  • 2,181
  • 2
  • 16
  • 42
  • 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`. – AskYous Mar 28 '19 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. – Maroš Beťko Mar 28 '19 at 18:08
  • Do you know the maximum depth before hand? Is it always 3? – AskYous Mar 28 '19 at 18:15
  • @AskYous yes that seems to be pretty similar, so it seems that this can't be done with css purely. – Maroš Beťko Mar 28 '19 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. – AskYous Mar 28 '19 at 18:18
  • Well I guess that just nesting enough `.a { ... .a{ ... .a { ...` would be sufficient then. – Maroš Beťko Mar 28 '19 at 18:19
  • Do you know what LESS and SASS is? It might make this way easier. They allow nested css and it will generate the CSS for you. – AskYous Mar 28 '19 at 18:21
  • Well I'm even using SASS in the example so yes :D Can I maybe use some loop or function from SASS to generate the nested classes? – Maroš Beťko Mar 28 '19 at 18:26
  • Maybe. I don't know. – AskYous Mar 28 '19 at 18:30
  • here is an idea : https://stackoverflow.com/a/52118738/8620333 – Temani Afif Mar 28 '19 at 19:52

1 Answers1

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>
feitla
  • 1,334
  • 1
  • 7
  • 12