Recently, I encountered a dilemma while enhancing the hover state of a link by adding an animated underline to it.
My approach involved using absolute position in the CSS, specifically setting bottom: 0;
in the ::after
pseudo class.
However, another requirement arose where I needed to implement Bootstrap's stretched link feature, which utilizes top: 0;
in the stretched-link::after
pseudo class.
Upon applying the stretched-link
class to the button, the link's hover state was activated, but the animated line overlapped the linked element, contrary to my intended effect.
This conflicting scenario has left me puzzled about the optimal solution to resolve the issue.
Here is an example of a Traditional Bootstrap 5 Card with stretched-link
applied:
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.0.2/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
<div class="row">
<div class="col-sm-6 col-md-4 col-lg-4 d-flex align-items-stretch">
<div class="card my-2">
<img src="https://placehold.co/400x50" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">Card title</h5>
<p class="card-text">Some quick example text.</p>
<a href="#" class="stretched-link">Go somewhere</a>
</div>
</div>
</div>
</div>
</div>
Meanwhile, here is a Traditional Bootstrap 5 Card with stretched-link
and the added animated hover state:
body {
font-size: 18px;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.container {
max-width: 800px;
}
.container p {
line-height: 1.5;
}
a {
text-decoration: none;
color: #005fec;
outline: 0;
position: relative;
display: inline-block;
}
a::after {
content: "";
position: absolute;
width: 100%;
transform: scaleX(0);
height: 1px;
bottom: 0;
left: 0;
background-color: #005fec;
transform-origin: bottom right;
transition: transform 0.25s ease-out;
}
a:hover::after {
transform: scaleX(1);
transform-origin: bottom left;
}
a:focus:not(:focus-visible) {
outline: 0;
}
a:focus-visible {
outline: 1px solid #005fec;
outline-offset: 2px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.0.2/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
<div class="row">
<div class="col-sm-6 col-md-4 col-lg-4 d-flex align-items-stretch">
<div class="card my-2">
<img src="https://placehold.co/400x50" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">Card title</h5>
<p class="card-text">Some quick example text.</p>
<a href="#" class="stretched-link">Go somewhere</a>
</div>
</div>
</div>
</div>
</div>