According to my understanding, the ::before
pseudo-element should be positioned below the element, while the ::after
pseudo-element should appear above it in terms of z-index.
In this particular scenario, I am attempting to darken just the background color (not the foreground color) when hovering over a button. Despite using ::before
, it still displays in front. Why is that the case? I am aware that I could resolve this by adjusting the z-index
, but as per this comment, which received 6 upvotes:
I think it's better to use :before so you get the right stacking order without playing with z-index.
I would expect not to have to do so, and the order should be correct from the outset?
.parent {
--my-color: red;
}
button {
color: blue;
background-color: var(--my-color);
padding: 8px 16px;
position: relative;
}
button:hover {
background-color: transparent;
}
button:hover::before {
display: block;
content: "";
position: absolute;
top: 0; left: 0; width: 50%; height: 100%; /* width is 50% for debugging (can see whats below) */
background-color: var(--my-color);
filter: brightness(80%);
}
<div class="parent">
<button type="button">CLICK ME</button>
</div>