I tried a lot of stuff, but I cannot figure this one out. I want to make a small red line that goes around a box of content indefinitely and stays basically inside the border. However, as the animation progresses, the line starts to change on its way towards the corner and not after. Here is the code:
#main {
min-height: 300px;
position: relative;
padding: 20px;
border: 2px solid transparent;
}
#main::after {
content: '';
position: absolute;
top: 0;
left: 0;
width: 10%;
height: 2px;
background-color: red;
animation: border-slide 4s linear infinite;
}
@keyframes border-slide {
0% {
top: 0;
left: 0;
width: 10%;
height: 2px;
}
25% {
top: 0;
left: 90%;
width: 2px;
height: 10%;
}
50% {
top: 90%;
left: 90%;
width: 10%;
height: 2px;
}
75% {
top: 0;
left: 0;
width: 2px;
height: 10%;
}
100% {
top: 0;
left: 0;
width: 10%;
height: 2px;
}
}
<div id="main">
Contents
</div>
I tried different methods, but basically, nothing helped. I just want that red line to go around the main content’s box, but I just cannot figure out how.
Edit: I want the line to smoothly go through the edge, curving at the edge. It is very similar to @NINE’s answer; it just appears on the right side after it finishes the top side. I want it to transition, curve, and not just appear on the next side, so the line isn’t always straight; it has to curve at the edge. I want it to always have the same speed.
2
Answers
I’m not sure, but,
Do you want something like this?
It seems necessary to adjust the speed when moving horizontally and when moving vertically.
Rather than trying to animate a line, or rather a set of lines trying to emulate a curve and going round a corner, CSS can basically do all that for you with a combination of conic gradients, animation and CSS variables.
What ‘rotates’ is the CSS variable, –border-angle, and the backgrounds use this to work out where to be.
This demo isn’t perfect, the line slightly ‘shrinks’ but it might be a good basis for getting what you want as the curvature is dealt with by CSS.
It is a simplified form of the method used in https://codepen.io/shshaw/pen/RwJwJJx which itself says was inspired by the mega buttons on https://turbo.build/
Apologies that I don’t have time at the moment to refine the outcome but hope it may point to a more perfect solution.