CSS HOVER TEXT CHANGE
Let's create a hover effect for an anchor (<a>
) as shown below. where the text "YEAH" slides in from the top with a background color change when the user hovers over the link. So let's create it:
write an HTML for anchor <a> tag:
<a href="#">hover me</a>
-
Anchor Element Styling (
a
):- Sets the background color, font size, display type, text decoration, text transformation, text color, border, padding, position, and overflow properties for the anchor element.
- This styles the anchor as a button-like element with a specific appearance.
/* Style for the anchor element */
a {
background-color: rgb(51, 49, 49);
font-size: 1.2rem;
display: inline-block;
text-decoration: none;
text-transform: uppercase;
color: #eee;
border: .2rem solid white;
padding: 1.5rem 3rem;
position: relative;
overflow: hidden;
}
T
-
Create a pseudo-element for the Hover Effect (
a::before
):- Creates a pseudo-element before the anchor element (the
::before
pseudo-element). - Sets its content to "YEAH," positioning it at the top-left corner of the anchor element.
- Makes it take up the full width and height of the anchor element.
- Uses flex properties to center the "YEAH" text vertically and horizontally.
- Sets a background color (
#f83939
) and initially moves it above the anchor usingtransform: translateY(-100%)
. - Applies a transition effect with a duration of 0.8 seconds for all properties.
- Creates a pseudo-element before the anchor element (the
/* Pseudo-element for the hover effect */
a::before {
content: 'YEAH ';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
z-index: 1;
background-color: #f83939;
transform: translateY(-100%); /* Initially, hide above the anchor */
transition: all .8s; /* Smooth transition for all properties over 0.8 seconds */
}
-
Hover Effect (
a:hover::before
):- When the user hovers over the anchor element, this CSS block is activated.
- It moves the pseudo-element with "YEAH" text back to its original position (translateY(0)), causing it to slide in from the top.
- This creates a hover effect where the text "YEAH" appears with a background color change when hovering over the link.
/* Hover effect */
a:hover::before {
transform: translateY(0); /* Move the pseudo-element to its original position */
}
Now when you hover over the link, the "YEAH" text slides in from the top, and the background color changes to create a visually appealing interaction.
See Demo: Codepen