Zucker
Zucker

Reputation: 53

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

Upvotes: 2

Views: 205

Answers (2)

monty
monty

Reputation: 41

You would probably need to use JS or jQuery.

For example, with jQuery you could use a really simple function like this which increase the z-index for each block by one:

$(".block").each(function(i) {
  i++
  $(this).css("z-index", i);
});
.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;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<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>

Upvotes: 0

Temani Afif
Temani Afif

Reputation: 273513

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?

Upvotes: 3

Related Questions