1

I have a seemingly silly issue where I want to have a pseudo-element beneath a button that just has a border, and creates a "shadow" when hovered. However, when I add a border to the pseudo-element, the border itself seems to ignore the z-index property and show through the button.

Here's a JSFiddle of the "issue"

button {
  padding: 20px;
  position: relative;
  z-index: 1;
  background: #2c3e50;
  color: white;
  border: none;
  outline: none;
  border-radius: 50px;
}

button::after {
  position: absolute;
  content: '';
  inset: 0;
  border-radius: 50px;
  border: 3px solid #9b59b6;
  z-index: -1;
  transition: 300ms ease;
}

button:hover::after {
  transform: translateX(10px) translateY(10px);
}
<button>
    My button
</button>

What I need is for the purple border to "hide" beneath the button and show only on hover. I tried using opacity but that doesn't solve the issue as the border still shows "above" the button. I also tried using box-shadow instead of border but the results are the same.

kiner_shah
  • 3,939
  • 7
  • 23
  • 37
F. Bill
  • 61
  • 7

2 Answers2

1

I removed the z-index on the button and it seems to be working.

button {
  padding: 20px;
  position: relative;
  background: #2c3e50;
  color: white;
  border: none;
  outline: none;
  border-radius: 50px;
  display:block;
}

button::after {
  position: absolute;
  content: '';
  inset: 0;
  border-radius: 50px;
  border: 3px solid #9b59b6;
  z-index: -1;
  transition: 300ms ease;
}

button:hover::after {
  transform: translateX(10px) translateY(10px);
}
<button>
    My button
</button>
Youssouf Oumar
  • 29,373
  • 11
  • 46
  • 65
  • its the fastest and most simple solution – jac wida Dec 04 '21 at 10:09
  • Alright this seems to be working, BUT... for some reason, when I transfer the code to my actual website code (which is naturally a bit more complex) the border won't show up on hover! – F. Bill Dec 04 '21 at 10:11
1

I've found the issue, the problem is that the: after z-index will be always relative to parent '', in order to use z-index you will have to make 2 children with different z-index to arrange them inside their container,

In this case, I've created ':before' with the same style of button and I gave it z-index:1; Just add this :

button::before {
  content:'My button';
  padding:20px;
  background:#2c3e50;
  color:white;
  border:none;
  outline:none;
  border-radius:50px;
  position: absolute;
  top:0;
  left:0;
  z-index:1;
}