How can make z-index absolute even if there's transformation modifiers on the element?

39 Views Asked by At

In my codesnippit I want to make the red circle appear over the black box but under the text. The problem is when I add transform: translateZ(0px); to the black box, my z-index: 2; CSS on my text doesn't work anymore. I was wondering if there was a way for one thing to appear on top of another even if they are being transformed. like no matter what Z space each element is in I want the text to appear on top of the red circle.

I was wondering if there is something more powerful than z-index I can use on the text without adding an extra div or anything.

body {
  width: 100vw;
  height: 100vh;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}

.black-box {
  width: 200px;
  height: 150px;
  background: black;
  display: flex;
  justify-content: center;
  align-items: center;
  transform: translateZ(0px);
  border-radius: 20px;
}

.black-box p {
  font-size: 30px;
  z-index: 2;
}

.red-box {
  position: absolute;
  width: 100px;
  height: 100px;
  background: red;
  transform: translateX(-40px);
  z-index: 1;
  border-radius: 100%;
  opacity: 75%;
}
<div class="black-box">
  <p>hello</p>
</div>
<div class="red-box"></div>

1

There are 1 best solutions below

0
Chamalka Gunawardana On

Put the red-box class inside the black-box class

body {
  width: 100vw;
  height: 100vh;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}

.black-box {
  width: 200px;
  height: 150px;
  background: black;
  display: flex;
  justify-content: center;
  align-items: center;
  transform: translateZ(0px);
  border-radius: 20px;
}

.black-box p {
  font-size: 30px;
  z-index: 2;
}

.red-box {
  position: absolute;
  width: 100px;
  height: 100px;
  background: red;
  transform: translateX(-40px);
  z-index: 1;
  border-radius: 100%;
  opacity: 75%;
}
<div class="black-box">
  <p>hello</p>
  <div class="red-box"></div>
</div>