CSS @keyframes regel

Definition og brug

Gennem @keyframes-reglen kan du skabe en animation.

Princippet bag at skabe en animation er at gradvist ændre et sæt CSS-stil til et andet.

Under animationen kan du ændre dette CSS-stil flere gange.

Brug procentværdier til at specificere, hvornår ændringerne sker, eller brug nøgleordene "fra" og "til", hvilket er lig med 0% og 100%.

0% er starttiden for animationen, 100% er sluttiden for animationen.

Tip:For at få den bedste browserstøtte skal du altid definere vælgerne 0% og 100%.

Tip:Brug animationsegenskaberne til at kontrollere animationens udseende, og bind animationen til en vælger.

Note:!important-reglen ignoreres i nøgle rammer (se sidens sidste eksempel).

Se også:

CSS3教程:CSS3 animation

Eksempel

Eksempel 1

Make the div element move down at a constant speed:

@keyframes mymove {
  from {top: 0px;}
  to {top: 200px;}
}

Try it yourself

Example 2

Add multiple keyframe selectors in one animation:

@keyframes mymove {
  0%   {top: 0px;}
  25%  {top: 200px;}
  50%  {top: 100px;}
  75%  {top: 200px;}
  100% {top: 0px;}
}

Try it yourself

Example 3

Change multiple CSS styles in one animation:

@keyframes mymove {
  0%   {top: 0px; background: red; width: 100px;}
  100% {top: 200px; background: yellow; width: 300px;}
}

Try it yourself

Example 4

Multiple keyframe selectors with multiple CSS styles:

@keyframes mymove {
  0%   {top: 0px; left: 0px; background: red;}
  25%  {top: 0px; left: 100px; background: blue;}
  50%  {top: 100px; left: 100px; background: yellow;}
  75%  {top: 100px; left: 0px; background: green;}
  100% {top: 0px; left: 0px; background: red;}
}

Try it yourself

Example 5

Note:The !important rule is ignored in keyframes:

@keyframes myexample {
  from {top: 0px;}
  50%  {top: 100px !important;} /* Ignored */
  to   {top: 200px;}
}

Try it yourself

CSS syntax

@keyframes animationname {keyframes-selector {css-styles;}}

Property value

Value Description
animationname Required. Define the name of the animation.
keyframes-selector

Required. The percentage of animation duration.

Valid values:

  • 0-100%
  • from (same as 0%)
  • to (same as 100%)
css-styles Required. One or more valid CSS style properties.

Browsers' support

Chrome IE / Edge Firefox Safari Opera
43.0
4.0 -webkit-
10.0 16.0
5.0 -moz-
9.0
4.0 -webkit-
30.0
15.0 -webkit-
12.0 -o-