debute debute - 5 months ago 11
CSS Question

Overlap ::after and ::before with text in CSS

Goal: Make nice effect of hovering buttons in pure CSS, which will use

::after
and
::before
pseudo-elements. Look at this jsFiddle example to see, what I want to reach.

Code: Button will have some styling, also an
background-color
, which is turned off in this example.

.button {
display: inline-block;
position: relative;
height: 35px;
line-height: 35px;
padding: 0 15px;
/*background-color: white;*/
text-decoration: none;
color: black;
}


Problem: I want to use
background-color
and when I enable it, then I can't see pseudo-elements. It is like that, because these pseudo-elements have
z-index: -1;
, which put them behind the background. When I change
z-index
to
0
or
1
, then text is not visible.

What I can't do: I can't add new elements inside buttons (like
span
s), because this is one already running website and client decided to change the behavior of buttons, so here I am. There are tons of buttons in this website, so this is the reason, why I want to find solution with pseudo-elements, because trying to find every single button and change them would be inappropriate.

Answer

If i understood you well, this is what you are looking for:

.button {
    display: inline-block;
    position: relative;
    height: 35px;
    line-height: 35px;
    padding: 0 15px;
    /*background-color: white;*/
    text-decoration: none;
    color: black;
	border:1px solid;
}
a.button:before {
    content: " ";
    display: block;
    z-index: -1;
    position: absolute;
    height: 0%;
    top: 0;
    right: 0;
    left: 0;
    background: #ddd;
	transition: height 0.2s ease;
}

a.button:hover:before {
	height:100%;
}
<a href="#" class="button">TEST</a>

Comments