Animaciones CSS
- Página anterior Transiciones CSS
- Página siguiente Herramientas de información CSS
Animaciones CSS
CSS puede realizar efectos de animación en elementos HTML sin usar JavaScript o Flash!
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
Compatibilidad del navegador con animaciones
Los números en la tabla indican la versión del navegador que 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?
Las animaciones hacen que los elementos cambien gradualmente de un estilo a otro.
Puede cambiar libremente cualquier cantidad de propiedades CSS.
Para usar animaciones CSS, debe especificar primero algunos cuadros clave para la animación.
Los cuadros clave contienen los estilos que posee el elemento en un tiempo específico.
regla @keyframes
Si en @keyframes
Las reglas especifican los estilos 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 estar vinculada a algún elemento.
El siguiente ejemplo vincula la animación "example" al 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; }
Atención:animation-duration
La propiedad define cuánto tiempo tarda la animación en completarse. Si no se especifica animation-duration
Si no se especifica la propiedad, la animación no se realizará, 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 0% (inicio) y 100% (final)), establecimos cuándo cambia el estilo.
También puede usar porcentajes. Al usar porcentajes, puede agregar tantas cambios de estilo como necesite.
El siguiente ejemplo cambiará el color de fondo del elemento <div> al 25%, al 50% y al 100% de la animación completada:
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 animación al elemento */ div { width: 100px; height: 100px; background-color: red; animation-name: example; animation-duration: 4s; }
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 animación al elemento */ div { width: 100px; height: 100px; position: relative; background-color: red; animation-name: example; animation-duration: 4s; }
Retrasar la animación
animation-delay
La propiedad especifica el tiempo de retraso antes de comenzar 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; }
Los valores negativos también son permitidos. Si se utiliza un valor negativo, la animación comenzará a reproducirse como si ya hubiera reproducido N segundos.
En el siguiente ejemplo, la animación comenzará a reproducirse como si ya hubiera reproducido 2 segundos:
Example
div { width: 100px; height: 100px; position: relative; background-color: red; animation-name: example; animation-duration: 4s; animation-delay: -2s; }
Establecer 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 ejecuta 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; }
El siguiente ejemplo utiliza el valor "infinite" para que la animación se repita para siempre:
Example
div { width: 100px; height: 100px; position: relative; background-color: red; animation-name: example; animation-duration: 4s; animation-iteration-count: infinite; }
Reproducir animación en sentido inverso o alternativo
animation-direction
La propiedad especifica si la animación se reproduce hacia adelante, hacia atrás o de manera alternativa.
animation-direction
La propiedad puede aceptar los siguientes valores:
normal
- La animación se reproduce de manera normal (hacia adelante). Valor predeterminadoreverse
- La animación se reproduce en sentido inverso (hacia atrás)alternate
- La animación se reproduce primero hacia adelante y luego hacia atrásalternate-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; }
El siguiente ejemplo utiliza el valor "alternate" para que la animación se mueva 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; }
El siguiente ejemplo utiliza el valor "alternate-reverse" para que la animación se mueva 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; }
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
- Especificar una animación que comience lentamente, luego se acelere y luego termine lentamente (predeterminado)linear
- Especificar una animación en la que la velocidad sea la misma desde el principio hasta el finalease-in
- Especificar una animación que comience más lentamenteease-out
- Especificar una animación que termine más lentamenteease-in-out
- Especificar una animación que comience y termine más lentamentecubic-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;}
Especificar el modo de relleno de la animación
Las animaciones CSS no afectarán al elemento antes de que se reproduzca el primer fotograma clave ni después de que se reproduzca el último fotograma clave.animation-fill-mode
la propiedad puede cubrir 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 aplicará 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á simultáneamente las reglas hacia adelante y hacia atrás, expandiendo las propiedades de animación en ambas direcciones.
El siguiente ejemplo permite que el elemento <div> mantenga 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; }
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; }
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; }
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; }
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; }
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 plays forward, backward, or alternates. |
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 start, after end, or both). |
animation-iteration-count | Define the number of times the animation should be played. |
animation-name | Define the name of the @keyframes animation. |
animation-play-state | Especifica si la animación se ejecuta o se detiene. |
animation-timing-function | Especifica la curva de velocidad de la animación. |
- Página anterior Transiciones CSS
- Página siguiente Herramientas de información CSS