I have a horizontal line which I am animating. The final part of the animation shrinks the line to a length (width) of zero. However, my code makes it shrink towards the centre, but instead I want the line to shrink towards the right-hand side. How can I achieve this?
body {
margin: 0;
background: black;
}
.white-line {
position: absolute;
top: 50%;
left: 50%;
width: 5px;
height: 10px;
background-color: red;
transform: translate(-50%, -50%);
animation: expandLine 0.3s ease-in-out forwards 1.2s, moveUp 1.5s ease-in-out forwards 1.41s, contractLine 0.5s ease-in-out forwards 3.3s;
z-index: 1000;
}
@keyframes expandLine {
100% {width: 100%; opacity: 1;}
}
@keyframes moveUp {
100% {top: 0%;}
}
@keyframes contractLine {
100% {width: 0;}
}
<div class="white-line"></div>
The reason it is shrinking towards the centre is because that’s where the line is positioned, at left: 50%
. So, while shrinking the width you’ll need to simultaenously move the position of your line across to the right side, or left: 100%
.
In your contractLine
animation, add the declaration left: 100%
.
body {
margin: 0;
background: black;
}
.white-line {
position: absolute;
top: 50%;
left: 50%;
width: 5px;
height: 10px;
background-color: red;
transform: translate(-50%, -50%);
animation: expandLine 0.3s ease-in-out forwards 1.2s, moveUp 1.5s ease-in-out forwards 1.41s, contractLine 0.5s ease-in-out forwards 3.3s;
z-index: 1000;
}
@keyframes expandLine {
100% {width: 100%; opacity: 1;}
}
@keyframes moveUp {
100% {top: 0%; transform: translate(-50%, 0);}
}
@keyframes contractLine {
100% {width: 0; left: 100%;}
}
<div class="white-line"></div>
I have also added transform: translate(-50%, 0)
in the moveUp
animation, which prevents half the line disappearing off the top of the page.