@keyframes appear {
0% {
opacity: 0;
}
50% {
opacity: 1;
}
100% {
opacity: 0;
}
}
@keyframes appearFromTop {
0% {
opacity: 0;
transform: translateY(-500px);
border-radius: 50px;
}
30% {
opacity: 1;
transform: translateY(0);
}
50% {
border-radius: 10px;
}
100% {
opacity: 0;
transform: translateY(-500px);
border-radius: 50px;
}
}
.box {
width: 500px;
height: 60px;
background-color: black;
position: absolute;
top: 0;
bottom: 800px;
left: 0;
right: 0;
margin: auto;
transition: background-color 0.25s 0.25s ease-in-out;
}
.box--from-top {
animation: appearFromTop 5s 0.5s both;
}
I wish this animation would stay on the page for a few seconds and then fade away. So my question is: How can I do that? I think I tried everything. animation-delay is not working, animation-play-state is not working
CodePudding user response:
You can add "no-op" in the animation process: i.e., make the opacity be at 1 from the 10% to 90% of the animation timeline.
For the length of 5 second, it would mean that 80% of 5 seconds (that's 4 seconds) the element stays on full opacity, 0.5s to fade in and 0.5s to fade out.
box{
animation: 5s linear 0s 1 normal fade-in-out;
opacity: 0;
}
@keyframes fade-in-out{
0% {opacity: 0}
10% {opacity: 1}
90% {opacity: 1}
100% {opacity: 0}
}
<box> Hello, world! </box>
CodePudding user response:
Something like this? You can make a long animation and only animate in between certain percentage values.
For example: A 5 second animation where a fade-in happens between 0-20% and a fade-out between 80-100% would mean it fades in for 1 second, remains on screen for 3, fades out for 1 second again.
.box {
width: 500px;
height: 60px;
background-color: black;
position: absolute;
top: -60px;
left: 0;
margin: auto;
}
.box--from-top {
animation: inOut 5s;
}
@keyframes inOut {
0% {
transform: translateY(0);
opacity: 0;
}
20% {
transform: translateY(50px);
opacity: 1;
}
80% {
transform: translateY(50px);
opacity: 1;
}
100% {
transform: translateY(0);
opacity: 0;
}
}
<div ></div>
It'd also be possible to have a separate fade-in and fade-out animations CSS animation with a little bit of javascript do the trick for you. This can be more flexible in general.
const box = document.querySelector('.box');
setTimeout(function(){
box.classList.remove('fadein');
box.classList.add('fadeout');
}, 5000);
.box {
width: 500px;
height: 60px;
background-color: black;
position: absolute;
top: 0;
left: 0;
margin: auto;
}
.fadein {
animation: fadein 1s;
}
.fadeout {
animation: fadeout 1s;
animation-fill-mode: forwards;
}
@keyframes fadein {
0% {
opacity: 0;
top: -60px;
}
100% {
top: 0;
opacity: 1;
}
}
@keyframes fadeout {
0% {
opacity: 1;
}
100% {
top: -60px;
opacity: 0;
}
}
<div ></div>