CSS underline in and out effect from left to right when the mouse hovers
CSS underline effect from left to right when hovering
HTML Structure
First, we need to prepare a simple HTML structure, for example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>CSS Underline Effect on Hover from Left to Right</title>
</head>
<body>
<div class="underline">Hover Effect</div>
</body>
</html>
CSS Style
Next, we use CSS to define the underline style and animation effect:
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
font-family: Arial, sans-serif;
background-color: #f7f7f7;
}
.underline {
position: relative;
font-size: 2em;
cursor: pointer;
}
.underline::before,
.underline::after {
content: '';
position: absolute;
left: 0;
bottom: 0;
height: 2px;
background-color: #333;
transition: width 0.3s ease;
width: 0;
}
.underline::after {
bottom: auto;
top: 0;
}
.underline:hover::before {
width: 100%;
}
.underline:hover::after {
width: 100%;
}
In the above CSS code, we first set the styles of the .underline
element, including font size, cursor style, and so on. We then use the ::before
and ::after
pseudo-elements to create two horizontal underlines, setting their width to 0. We then use the transition
property to adjust the width of the underlines.
Next, we use .underline:hover::before
and .underline:hover::after
to define the width of the underline when the mouse hovers over it. When the mouse hovers over the .underline
element, the underline’s width gradually increases from 0 to 100%, creating a sliding effect from left to right.
Runtime Effect
Save the above HTML and CSS code in the same directory, naming them index.html
and style.css
, respectively. Open the index.html
file in a browser and you’ll see the underline appear from left to right when you hover your mouse.
In practice, you can further customize the underline style according to your needs, such as changing the underline color, height, animation speed, and more, to achieve a more ideal effect.
Using this simple CSS technique, we can easily achieve an underline effect that moves from left to right when the mouse hovers, adding a sense of dynamism and style to the webpage and enhancing the user experience.