So, I was trying to create a basic hover animation in my navbar for a React app using pseudo elements of CSS. When I tried to implement the code, this problem showed and I don't understand the exact reason behind it.
I have used Bootstrap to create a basic layout and then tried to implement my own CSS.
JSX code:
<div className="collapse navbar-collapse" id="navbarSupportedContent">
<ul className="navbar-nav me-auto mb-2 mb-lg-0">
<li className="nav-item">
<a className="menu nav" aria-current="page" href="#">Home</a>
</li>
<li className="nav-item">
<a className="menu nav" href="#">Products</a>
</li>
</ul>
</div>
CSS code:
#navbarSupportedContent {
position : relative;
top : 5.78px;
margin-left : .4em;
}
.nav{
font-family : var(--font-1);
font-size : 1.2em;
color : var(--color-1);
text-decoration : none;
}
#navbarSupportedContent ul li:not(:last-child) {
margin-right : 1em;
}
.menu::before{
content : "";
position : absolute;
bottom : 0;
left : 0;
width : 0;
height : 4px;
background : var(--color-1);
border-radius : 50px;
transform : translateY(-4px);
transition : width .5s ease;
}
.menu:hover::before {
width : 100%;
}
I was expecting:

I got:

What is the error? How can I fix it?
You need to use
:afterpseudo class instead, removeposition: absoluteand adddisplay: inline-blockto the pseudo element and add the pseudo element after theliinstead of the.menuclass. I also added the required media query to make it look right when the navbar is collapsed. The changes: