m0bi5
m0bi5

Reputation: 9452

Preserve the last keyframe property in CSS animations

I have a div with some text:

<div>Rain.js</div>

and its CSS:

div {
  -webkit-animation: fadein 2s;
  color:black;
  font-size:70px;
}

I want to make the div fade in so I made an animation fadein to change the opacity of the div from 0 to 0.1

@keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 0.1; }
}

As you can see here the fadein from opacity 0 to 0.1 occurs in 2 seconds as expected. But after 2 seconds the opacity goes from 0.1 to 1.

1) Why does this happen?

2) How can I prevent this from happening?

Upvotes: 1

Views: 1903

Answers (3)

m4n0
m4n0

Reputation: 32255

You have not added animation-fill-mode: forwards to preserve the final state of the animation.

Since there are no default properties set for opacity in your CSS rules and the animation-fill-mode by default is none, the element takes the default opacity value of 1 after the animation is finished.

JSfiddle Demo

div {
  animation: fadein 2s;
  color: black;
  font-size: 70px;
  animation-fill-mode: forwards;
}
@keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 0.1;
  }
}
<div>Rain.js</div>

Upvotes: 4

Bob Baxley
Bob Baxley

Reputation: 3751

After the fadein is done, the div takes on its specified values.

You simply need to make the opacity of the div equal to the final key frame opacity value.

div
{
    -webkit-animation: fadein 2s;
    color:black;
    font-size:70px;
    opacity:0.1;
}

Upvotes: 1

Ivanka Todorova
Ivanka Todorova

Reputation: 10219

When the animation ends it puts the div in his opacity default state, which is not set. (therefore it will be 1).

Add to your CSS on the div:

opacity: 0.1;

Demo: http://jsfiddle.net/qm3f6717/1/

Upvotes: 3

Related Questions