I have a button that gets underlined on hover. It works fine on desktop, but the underline is never visible when on mobile. What can I do to fix it?
Codepen of button working correctly
Gif of how underline disappears on mobile
Interestingly if you view the codepen in mobile mode, the underline also disappears.
html
<button id="google" class="button" onclick="window.location.href='https://www.google.com/;">
<span id="github" class="hover-underline-animation">Google</span>
<svg viewBox="0 0 46 16" xmlns="http://www.w3.org/2000/svg" id="arrow-horizontal">
<path fill="currentColor" transform="translate(30)" d="M8,0,6.545,1.455l5.506,5.506H-30V9.039H12.052L6.545,14.545,8,16l8-8Z" data-name="Path 10" id="Path_10"></path>
</svg>
</button>
css
.button {
border: none;
background: none;
margin-top: 9.5vh;
cursor: pointer;
}
/* Button text */
.button span {
letter-spacing: 0.2em;
font-size: 1.1vw;
font-weight: 500;
/* Padding at end of button text */
padding-right: 0.8vw;
text-transform: uppercase;
}
/* Button arrow */
.button svg {
height: 0;
width: 0;
/* transform: translateX(-0.6em);
transition: all 0.3s ease; */
}
.button:hover svg {
transform: translateX(0);
}
.button:active svg {
transform: scale(0.9);
}
/* Underline animation on hover */
.hover-underline-animation {
position: relative;
/* Padding from button text */
padding-bottom: 0.5em;
}
.hover-underline-animation:after {
content: '';
position: absolute;
width: 85%;
transform: scaleX(0);
/* Thickness of underline */
height: 0.15em;
bottom: 0;
left: 0;
transform-origin: bottom right;
transition: transform 0.25s ease-out;
background-color: black;
}
.button:hover .hover-underline-animation:after {
transform: scaleX(1);
transform-origin: bottom left;
}
I tried playing around with the CSS. If I change scaleX from 0 to 1 in .hover-underline-animation:after, it becomes visible. So I know the underline does exist. But the hover just doesn’t play in mobile.
2
Answers
The issue you’re experiencing with the hover underline animation not working on mobile devices is due to the fact that mobile devices typically don’t support hover interactions in the same way as desktop devices. On mobile, the hover state is triggered by tapping, and since there is no hover state, the underline animation is not being applied.
To address this issue, you can use CSS media queries to apply the underline animation by default on mobile devices. You can modify your CSS code as follows:
In this modified code, the underline animation will be applied by default on mobile devices using the
@media (hover: none)
query. This ensures that the underline is visible on mobile, regardless of the hover state. On desktop devices, the hover underline animation will still be triggered by hovering over the button.With this update, the underline animation should be visible on mobile devices, even without the hover interaction.