i basically am trying to place the after and before pseudo elements behind anchor tag but they are still appearing on upfront , even though i have allocated them z-index
a{
padding:1rem 1.5rem;
background-color:whitesmoke;
border-radius:12px;
text-decoration:none;
font-size:1.1rem;
color:black;
position:relative;
z-index:2;
user-select:none;
cursor:pointer;
}
a:hover::after{
content:'';
position:absolute;
height:50%;
width:50%;
bottom:2px;
right:3px;
box-shadow:5px 5px 40px 10px rgb(142, 224, 231);
transition:all 0.5s;
animation:shinny2 1s ease-in 1;
animation-fill-mode:forwards;
z-index: 0;
}
a:hover::before{
content:'';
position:absolute;
z-index:0;
height:50%;
width:50%;
top:2px;
left:3px;
box-shadow:-5px -5px 40px 10px rgb(142, 224, 231);
animation:shinny1 1s ease-in 1;
animation-fill-mode:forwards;
}
<a href="#">Foo</a>
2
Answers
Your
<a>
tag has thez-index
of2
, which is higher than the default valueauto
(which is0
if it has a stacking context).When you assign its child pseudo elements to
z-index: 0;
, even they’re smaller than2
, but they’re not going to compare thez-index
with its parent. (Otherwise you have to assign every of its ascendence with the same or higherz-index
in order to show them)Unless you give them a negative
z-index
, then they’ll be shown behind the parent, because they’re compared with the global stacking context instead of local.But using a negative
z-index
has a drawback, that it will be appeared behind every other elements but not only its parent, unless they have a even lowerz-index
(negative z-index hell).If don’t want to mess around with
z-index
, a workaround is to utilizetranslateZ
to put the pseudo elements behind its content, that will only be affected in the local 3d stacking context. So you don’t need to worry about the interations with other elements.Declaring
z-index: -1
on the pseudo-elements does the job.It appears that the z-index of the pseudo-elements is relative to the anchor. Giving the anchor
z-index: 0
keeps the stacking order of the elements while allowing the pseudo-elements to be underneath only the anchor.