How to apply z-index property so that the previous element overlaps the next?

I am wondering if there is any possibility to make previous block overlap the next one with CSS.

.container {
  padding: 70px;
  width: 500px;
  margin: auto;
  display: flex;
}

.block {
  margin-left: -30px;
  width: 200px;
  height: 100px;
  border: 1px dotted green;
  transform: skewY(20deg)
}

.red {
  background-color: red;
}

.green {
  background-color: green;
}

.blue {
  background-color: blue;
}

.black {
  background-color: black;
}
<div class="container">
  <div class="block red">Text...</div>
  <div class="block green">Text...</div>
  <div class="block blue">Text...</div>
  <div class="block black">Text...</div>
</div>

I could write for each block z-index with CSS, but what if the number of blocks will be for example one hundred?

Codepen:

https://codepen.io/pen/?template=zYoJVdp

Answer

Consider a 3d rotation:

.container {
  padding: 70px;
  width: 500px;
  margin: auto;
  display: flex;
  transform-style: preserve-3d; /*  important for the trick */
}

.block {
  margin-left: -30px;
  width: 200px;
  height: 100px;
  border: 1px dotted green;
  transform: rotateY(-1deg) skewY(20deg) /* a tiny rotation here */
}

.red {
  background-color: red;
}

.green {
  background-color: green;
}

.blue {
  background-color: blue;
}

.black {
  background-color: black;
}
<div class="container">
  <div class="block red">Text...</div>
  <div class="block green">Text...</div>
  <div class="block blue">Text...</div>
  <div class="block black">Text...</div>
</div>

More detail here : Why can’t an element with a z-index value cover its child?

Leave a Reply

Your email address will not be published. Required fields are marked *