Animaciones CSS
- Página anterior Transiciones CSS
- Página siguiente Herramientas de tooltip 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
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; }
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; }
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; }
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; }
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; }
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; }
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; }
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 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 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; }
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; }
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 finalease-in
- Especifique una animación que comience más lentamenteease-out
- Especifique una animación que acabe más lentamenteease-in-out
- Especifique una animación que comience y acabe 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 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; }
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 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. |
- Página anterior Transiciones CSS
- Página siguiente Herramientas de tooltip CSS