0

I created css button effect. I saw some people use negative z-index. I used it and it works properly but I'm confused by it's weird behavior.

I set '.container' position relative, '.btn' absolute,'a' relative and a::after absolute. I gave -1 z-index to 'a::after'. but why does not 'a::after' go under all elements. but when I set 'a::after' z-index 2 and 'a' z-index 3 button effect does not work as expected 'a::after' background color comes above the 'a'. why do these two methods work differently? why does not 'a::after' go under the all elements in first method.

Here is my css code:

.container{
  position: relative;
  width: 400px;
  height: 300px;
  background-color: #100f33;
  margin: 0 auto;
}
.btn{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.btn a{
  text-decoration: none;
  color: white;
  text-transform: uppercase;
  display: block;
  position: relative;
  padding: 20px;
  border: 1px solid #75230f;
  width: 80px;
  margin: 0 auto;
  overflow: hidden;
}
.btn a::after{
  display: block;
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  z-index: -1;
  transform: translate(-50%, -50%);
  width: 0;
  height: 100%;
  background-color: #840f38;
  transition: all 0.3s;
}
.btn a:hover::after{
  width: 100%;
}
<div class="container">
  <div class="btn">
    <a href="#">Click Me</a>
  </div>
</div>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415

1 Answers1

0

z-index is a so different topic in css. If you want send :after area go to under. You need give z-index property to a element. (After this change you will lost your clickable link.)

Because:

z-index always work with parent element. If you add z-index: 1 to .btn class. You will create new layer for all .btn child elements.

If you want more information about z-index and layers. You should visit here: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/Adding_z-index

M. Volkan
  • 19
  • 5