skip to Main Content

I would like to generate a "numbered list" of classes with z-index value corresponding to the list number, i.e.:

.layer1 {
   z-index: 10;
}

.layer2 {
   z-index: 9;
}

.layer3 {
   z-index: 8;
}

...

Is there a way to do this in CSS such that I don’t have to define all of the classes manually, but instead could use something like a for loop/pattern matching?

2

Answers


  1. The question seems kind of vague, but if you need to use the z-index to stack the list elements then why not style them directly?

    let container = document.getElementById("yourListContainerId")
    let listElements = Array.from(container.children)
    
    for (let index = 0; index < listElements.length; index++) {
        listElements[index].style.zIndex = listElements.length - index
    }
    

    Creating an Array from teh children property of the parent element will ensure that the elements don’t get scrambled by using the index of the for loop to access the DOM elements from the listElements array. From there you assign the z-index to each element style starting at the top (listElements.length) and subtracting the index as the loop progresses. Let me know if this works, cheers!

    edit: if for some reason you need to give a class to each element just add the following inside the loop:

    listElements[index].classList.add(`layer${index}`)
    
    Login or Signup to reply.
  2. You can’t do loops with pure CSS, but if you are using something like SASS then you can do like:

    $total_layers_count: 10;
    
    @for $i from $total_layers_count through 1 {
        .layer#{$i}
        {
            z-index:abs($i - $total_layers_count);
        }
    }
    

    Transpiled

    .layer10 {
      z-index: 0;
    }
    
    .layer9 {
      z-index: 1;
    }
    
    .layer8 {
      z-index: 2;
    }
    
    .layer7 {
      z-index: 3;
    }
    
    .layer6 {
      z-index: 4;
    }
    
    .layer5 {
      z-index: 5;
    }
    
    .layer4 {
      z-index: 6;
    }
    
    .layer3 {
      z-index: 7;
    }
    
    .layer2 {
      z-index: 8;
    }
    
    .layer1 {
      z-index: 9;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search