Animate 2 side borders on hover

Viewed 286

I have an element with a right and bottom border, which I'm trying to animate on hover. The animation I'd like and have seen examples of is where the border line is drawn left to right and top to bottom, however, all of these examples use four borders with box-shadows that can't be used on two sides only. Is it possible to animate just two? This is how my border is styled at the moment:

HTML:

a {
    display: block;
}

img {
    border-width: 12px;
    border-style: solid;
    border-top-color: blue;
    border-right-color: blue;
    border-bottom-color: transparent;
    border-left-color: transparent;
    width: 320px;
    transition: all 0.5s ease;
}
<a href="#"><img src="https://placehold.it/280x170" /></a>

3 Answers

You can animate border something like below snippet with help of ::before and ::after pseudo-elements.

a {
    display: inline-block;
    position: relative;
    overflow: hidden;
    padding: 12px;
}
a::before, a::after {
    content: "";
    position: absolute;
    transition: all 0.5s ease;
    background: blue;
}
a::before {
    width: 100%;
    height: 12px;
    top: 0;
    left: 120%;
    transform: skewX(45deg);
}
a::after {
    width: 12px;
    height: 100%;    
    left: auto;
    right: 0;
    bottom: 120%;
    transform: skewY(45deg);
}
a:hover::before{
    left: 6px;
}
a:hover::after{
    bottom: 6px;
}
img {
    width: 320px;
    display: block;
}
<a href="#">
    <img src="https://placehold.it/280x170">
</a>

A simple background animation can do it:

img {
    padding: 12px;
    background:
      linear-gradient(45deg,transparent 9px,blue 0),
      linear-gradient(45deg,transparent 9px,blue 0);
    background-position:top right;
    background-repeat:no-repeat;
    background-size:0% 12px,12px 0%;
    width: 320px;
    transition: all 0.5s ease;
}
img:hover {
    background-size:100% 12px,12px 100%;

}
<img src="https://placehold.it/280x170" >

That you can optimize with CSS variables:

img {
    --b:12px; /* border width */
    --c:blue; /* border color */
    
    --g:linear-gradient(45deg,transparent calc(var(--b)/1.41),var(--c) 0) no-repeat 100% 0;
    padding: var(--b);
    background:var(--g)/var(--t,0%) var(--b) ,var(--g)/var(--b) var(--t,0%);
    transition: all 0.5s ease;
}
img:hover {
    --t:100%;
}
<img src="https://placehold.it/230x170" >
<img src="https://placehold.it/100x170" style="--b:15px;--c:red;">
<img src="https://placehold.it/150x150" style="--b:25px;--c:green;">

You can use the combo of pseudo elements like ::before and ::after as listed below by @raeesh alam; or see if you can do it with only using hover effect.

a:hover {
    ...
}
Related