Search code examples
htmlcssz-index

How to make z-index of the blocks below to be less than the one of the block above


Task description

There are number of block which contain absolutely positioned elements. These absolutely positioned elements should overlap the absolutely positioned elements contained in the blocks below.

The solution to manually give z-indexes to the blocks is not good because the number of blocks is dynamic.

Are there any other solutions?

Attached code snippet for the task to be more clear. Please ask if you need more clarification on the task.

.wrapper {
  position: relative;
  width; 100%;
}

.inner {
  position: absolute;
  background: yellow;
  top: 0;
  right: 50px;
  height: 30px;
 }
 
 .inner.green {
   background: green;
 }
<div class="wrapper">
  Some content 1
  <div class="inner">Should be above</div>
</div>
<div class="wrapper">
  Some content 2
  <div class="inner green">Should be below</div>
</div>


Solution

  • You will need a counter that will be equal to the number of blocks that you will render, example:

    5 boxes - var counter = boxes.length
    

    And then while you iterate and render the boxes add:

    style="z-index:[counter];" to the box 
    and counter--
    

    You should have something like:

    box1 - z-index: 5
    box2 - z-index: 4
    etc...