Animaciones CSS

Animaciones CSS

CSS puede realizar efectos de animación en elementos HTML sin usar JavaScript o Flash!

CSS

En este capítulo, aprenderá lo siguiente:

  • @keyframes
  • animation-name
  • animation-duration
  • animation-delay
  • animation-iteration-count
  • animation-direction
  • animation-timing-function
  • animation-fill-mode
  • animation

Soporte del navegador para animaciones

Los números en la tabla indican la versión del navegador que primero admite completamente la propiedad.

Property Chrome IE Firefox Safari Opera
@keyframes 43.0 10.0 16.0 9.0 30.0
animation-name 43.0 10.0 16.0 9.0 30.0
animation-duration 43.0 10.0 16.0 9.0 30.0
animation-delay 43.0 10.0 16.0 9.0 30.0
animation-iteration-count 43.0 10.0 16.0 9.0 30.0
animation-direction 43.0 10.0 16.0 9.0 30.0
animation-timing-function 43.0 10.0 16.0 9.0 30.0
animation-fill-mode 43.0 10.0 16.0 9.0 30.0
animation 43.0 10.0 16.0 9.0 30.0

¿Qué es la animación CSS?

La animación hace que el elemento cambie gradualmente de un estilo a otro.

Puede cambiar cualquier número de propiedades CSS.

Para usar animaciones CSS, debe especificar primero algunos cuadros clave para la animación.

Los cuadros clave contienen los estilos que tiene el elemento en un momento específico.

regla @keyframes

Si en @keyframes La regla especifica el estilo CSS, y la animación cambiará gradualmente del estilo actual al nuevo estilo en un tiempo específico.

Para que la animación funcione, debe asociarla con algún elemento.

El siguiente ejemplo asocia la animación "example" con el elemento <div>. La animación durará 4 segundos, cambiando gradualmente el color de fondo del elemento <div> de "red" a "yellow":

Example

/* Código de animación */
@keyframes example {
  from {background-color: red;}
  to {background-color: yellow;}
}
/* Aplicar efectos de animación a este elemento */
div {
  width: 100px;
  height: 100px;
  background-color: red;
  animation-name: example;
  animation-duration: 4s;
}

Try It Yourself

Atención:animation-duration La propiedad define cuánto tiempo toma completar la animación. Si no se especifica animation-duration Si no se especifica la propiedad, la animación no se producirá, ya que el valor predeterminado es 0s (0 segundos).

En el ejemplo anterior, mediante la utilización de los términos clave "from" y "to" (que representan el 0% (inicio) y el 100% (final)), configuramos cuándo cambia el estilo.

También puede usar valores porcentajes. Al usar porcentajes, puede agregar tantas modificaciones de estilo como necesite.

El siguiente ejemplo cambiará el color de fondo del elemento <div> cuando el animación complete el 25%, el 50% y cuando complete el 100%:

Example

/* Código de animación */
@keyframes example {
  0%   {background-color: red;}
  25% {background-color: yellow;}
  50%  {background-color: blue;}
  100% {background-color: green;}
}
/* Aplicar el elemento animado */
div {
  width: 100px;
  height: 100px;
  background-color: red;
  animation-name: example;
  animation-duration: 4s;
}

Try It Yourself

El siguiente ejemplo cambiará el color de fondo y la posición del elemento <div> cuando la animación haya completado el 25%, el 50% y el 100%:

Example

/* Código de animación */
@keyframes example {
  0%   {background-color:red; left:0px; top:0px;}
  25%  {background-color:yellow; left:200px; top:0px;}
  50%  {background-color:blue; left:200px; top:200px;}
  75%  {background-color:green; left:0px; top:200px;}
  100% {background-color:red; left:0px; top:0px;}
}
/* Aplicar el elemento animado */
div {
  width: 100px;
  height: 100px;
  position: relative;
  background-color: red;
  animation-name: example;
  animation-duration: 4s;
}

Try It Yourself

Retrasar la animación

animation-delay La propiedad especifica el tiempo de retraso antes de que comience la animación.

El siguiente ejemplo tiene un retraso de 2 segundos antes de comenzar la animación:

Example

div {
  width: 100px;
  height: 100px;
  position: relative;
  background-color: red;
  animation-name: example;
  animation-duration: 4s;
  animation-delay: 2s;
}

Try It Yourself

Los valores negativos también son permitidos. Si se utiliza un valor negativo, la animación comenzará a reproducirse como si ya se hubiera reproducido N segundos.

En el siguiente ejemplo, la animación comenzará a reproducirse como si ya se hubiera reproducido 2 segundos:

Example

div {
  width: 100px;
  height: 100px;
  position: relative;
  background-color: red;
  animation-name: example;
  animation-duration: 4s;
  animation-delay: -2s;
}

Try It Yourself

Configurar el número de veces que debe ejecutarse la animación

animation-iteration-count La propiedad especifica el número de veces que debe ejecutarse la animación.

El siguiente ejemplo ejecutará la animación 3 veces antes de detenerse:

Example

div {
  width: 100px;
  height: 100px;
  position: relative;
  background-color: red;
  animation-name: example;
  animation-duration: 4s;
  animation-iteration-count: 3;
}

Try It Yourself

El siguiente ejemplo utiliza el valor "infinite" para que la animación se ejecute para siempre:

Example

div {
  width: 100px;
  height: 100px;
  position: relative;
  background-color: red;
  animation-name: example;
  animation-duration: 4s;
  animation-iteration-count: infinite;
}

Try It Yourself

Ejecutar animación en sentido inverso o alternativo

animation-direction La propiedad especifica si la animación se reproducirá hacia adelante, hacia atrás o alternativamente.

animation-direction La propiedad puede aceptar los siguientes valores:

  • normal - La animación se reproduce normalmente (hacia adelante). Valor predeterminado
  • reverse - La animación se reproduce en sentido inverso (hacia atrás)
  • alternate - La animación se reproduce primero hacia adelante y luego hacia atrás
  • alternate-reverse - La animación se reproduce primero hacia atrás y luego hacia adelante

El siguiente ejemplo ejecutará la animación en la dirección opuesta (hacia atrás):

Example

div {
  width: 100px;
  height: 100px;
  position: relative;
  background-color: red;
  animation-name: example;
  animation-duration: 4s;
  animation-direction: reverse;
}

Try It Yourself

El siguiente ejemplo utiliza el valor "alternate" para que la animación se ejecute primero hacia adelante y luego hacia atrás:

Example

div {
  width: 100px;
  height: 100px;
  position: relative;
  background-color: red;
  animation-name: example;
  animation-duration: 4s;
  animation-iteration-count: 2;
  animation-direction: alternate;
}

Try It Yourself

El siguiente ejemplo utiliza el valor "alternate-reverse" para que la animación se ejecute primero hacia atrás y luego hacia adelante:

Example

div {
  width: 100px;
  height: 100px;
  position: relative;
  background-color: red;
  animation-name: example;
  animation-duration: 4s;
  animation-iteration-count: 2;
  animation-direction: alternate-reverse;
}

Try It Yourself

Especificar la curva de velocidad de la animación

animation-timing-function La propiedad especifica la curva de velocidad de la animación.

animation-timing-function La propiedad puede aceptar los siguientes valores:

  • ease - Especifique una animación que comience lentamente, luego se acelere y luego termine lentamente (por defecto)
  • linear - Especifique una animación donde la velocidad es la misma desde el principio hasta el final
  • ease-in - Especifique una animación que comience más lentamente
  • ease-out - Especifique una animación que acabe más lentamente
  • ease-in-out - Especifique una animación que comience y acabe más lentamente
  • cubic-bezier(n,n,n,n) - Ejecute los valores que defina en la función de bezier de tres puntos.

Los siguientes ejemplos muestran algunas curvas de velocidad diferentes que se pueden usar:

Example

#div1 {animation-timing-function: linear;}
#div2 {animation-timing-function: ease;}
#div3 {animation-timing-function: ease-in;}
#div4 {animation-timing-function: ease-out;}
#div5 {animation-timing-function: ease-in-out;}

Try It Yourself

Especificar el modo de relleno de la animación

Las animaciones CSS no afectarán al elemento antes de la reproducción del primer fotograma clave ni después de la reproducción del último fotograma clave.animation-fill-mode la propiedad puede sobrescribir este comportamiento.

Cuando no se reproduce la animación (antes de comenzar, después de finalizar, o ambos al finalizar),animation-fill-mode La propiedad especifica el estilo del elemento objetivo.

La propiedad animation-fill-mode puede aceptar los siguientes valores:

  • none - Valor predeterminado. La animación no aplica ningún estilo al elemento antes o después de su ejecución.
  • forwards - El elemento mantendrá los valores de estilo establecidos por el último fotograma clave (dependiendo de animation-direction y animation-iteration-count).
  • backwards - El elemento obtendrá los valores de estilo establecidos por el primer fotograma clave (dependiendo de animation-direction) y mantendrá ese valor durante el retraso de la animación.
  • both - La animación seguirá las reglas tanto hacia adelante como hacia atrás, expandiendo las propiedades de animación en ambas direcciones.

El siguiente ejemplo muestra cómo el elemento <div> mantiene los valores de estilo del último fotograma clave al final de la animación:

Example

div {
  width: 100px;
  height: 100px;
  background: red;
  position: relative;
  animation-name: example;
  animation-duration: 3s;
  animation-fill-mode: forwards;
}

Try It Yourself

The following example makes the <div> element obtain the style value set by the first keyframe before the animation starts (during the animation delay):

Example

div {
  width: 100px;
  height: 100px;
  background: red;
  position: relative;
  animation-name: example;
  animation-duration: 3s;
  animation-delay: 2s;
  animation-fill-mode: backwards;
}

Try It Yourself

The following example makes the <div> element obtain the style value set by the first keyframe before the animation starts, and retain the style value of the last keyframe at the end of the animation:

Example

div {
  width: 100px;
  height: 100px;
  background: red;
  position: relative;
  animation-name: example;
  animation-duration: 3s;
  animation-delay: 2s;
  animation-fill-mode: both;
}

Try It Yourself

Animation Shorthand Properties

The following example uses six animation properties:

Example

div {
  animation-name: example;
  animation-duration: 5s;
  animation-timing-function: linear;
  animation-delay: 2s;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}

Try It Yourself

Using the shorthand animation The property can also achieve the same animation effect as the previous example:

Example

div {
  animation: example 5s linear 2s infinite alternate;
}

Try It Yourself

CSS Animation Properties

The following table lists the @keyframes rules and all CSS animation properties:

Property Description
@keyframes Define the animation mode.
animation Set a shorthand property for all animation properties.
animation-delay Define the delay before the animation starts.
animation-direction Define whether the animation is played forward, backward, or alternately.
animation-duration Define the time it should take for the animation to complete one cycle.
animation-fill-mode Define the style of the element when the animation is not playing (before, after, or both).
animation-iteration-count Define the number of times the animation should play.
animation-name Define the name of the @keyframes animation.
animation-play-state Define si la animación se ejecuta o se detiene.
animation-timing-function Define la curva de velocidad de la animación.