Animaciones CSS


Tabla de contenido

    Mostrar tabla de contenidos


Animaciones CSS

¡CSS permite la animación de elementos HTML sin usar JavaScript o Flash!

CSS

En este capítulo aprenderá sobre las siguientes propiedades:

  • @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 de la tabla especifican la primera versión del navegador que admite totalmente la propiedad.

Property
@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é son las animaciones CSS?

Una animación permite que un elemento cambie gradualmente de un estilo a otro.

Puedes cambiar tantas propiedades CSS como quieras, tantas veces como quieras.

Para utilizar la animación CSS, primero debe especificar algunos fotogramas clave para el animación.

Los fotogramas clave contienen qué estilos tendrá el elemento en determinados momentos.


La regla @keyframes

Cuando especifica estilos CSS dentro de @keyframes regla, la animación cambiará gradualmente del estilo actual al nuevo estilo en ciertos momentos.

Para que una animación funcione, debe vincularla a un elemento.

El siguiente ejemplo vincula la animación "ejemplo" al elemento <div>. La animación durará 4 segundos y cambiará gradualmente el color de fondo del elemento <div> de "rojo" a "amarillo":

Ejemplo

/* The animation code */
@keyframes example {
  from {background-color: red;}
   
to {background-color: yellow;}
}
/* The element to apply the animation to */
div {
  width: 100px;
  height: 100px;
  
background-color: red;	animation-name: example;
  animation-duration: 4s;
}

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<head>
<style> 
div {
  width: 100px;
  height: 100px;
  background-color: red;
  animation-name: example;
  animation-duration: 4s;
}

@keyframes example {
  from {background-color: red;}
  to {background-color: yellow;}
}
</style>
</head>
<body>

<h1>CSS Animation</h1>

<div></div>

<p><b>Note:</b> When an animation is finished, it goes back to its original style.</p>

</body>
</html>


Nota: La propiedad animation-duration define cuánto tiempo debe tardar en completarse una animación. Si no se especifica la propiedad animation-duration, no se producirá ninguna animación, porque el valor predeterminado es 0s (0 segundos).

En el ejemplo anterior hemos especificado cuándo cambiará el estilo usando las palabras clave "desde" y "hasta" (que representan 0% (inicio) y 100% (completo)).

También es posible utilizar el porcentaje. Usando el porcentaje, puedes agregar tantos El estilo cambia como quieras.

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

Ejemplo

/* The animation code */
@keyframes example
{
  0%   {background-color: red;}
   
25%  {background-color: yellow;}
  50%  {background-color: blue;}
  100% {background-color: green;}
}
/* The element to apply the animation to */
div {
  
width: 100px;
  height: 100px;
  background-color: red;
  animation-name: example;
  animation-duration: 4s;
}

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<head>
<style>
div {
  width: 100px;
  height: 100px;
  background-color: red;
  animation-name: example;
  animation-duration: 4s;
}

@keyframes example {
  0%   {background-color: red;}
  25%  {background-color: yellow;}
  50%  {background-color: blue;}
  100% {background-color: green;}
}
</style>
</head>
<body>

<h1>CSS Animation</h1>

<div></div>

<p><b>Note:</b> When an animation is finished, it goes back to its original style.</p>

</body>
</html>


El siguiente ejemplo cambiará tanto el color de fondo como la posición del <div> elemento cuando la animación está completa al 25%, al 50% y nuevamente cuando la animación está completa al 100%:

Ejemplo

/* The animation code */
@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;}
}
/* The element to apply the animation to */
div {
  
width: 100px;
  height: 100px;
  
position: relative;
  background-color: red;
  animation-name: example;
  animation-duration: 4s;
}

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<head>
<style> 
div {
  width: 100px;
  height: 100px;
  background-color: red;
  position: relative;
  animation-name: example;
  animation-duration: 4s;
}

@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;}
}
</style>
</head>
<body>

<h1>CSS Animation</h1>

<div></div>

<p><b>Note:</b> When an animation is finished, it goes back to its original style.</p>

</body>
</html>




Retrasar una animación

La propiedad animation-delay especifica un retraso para el inicio de una animación.

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

Ejemplo

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

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<head>
<style> 
div {
  width: 100px;
  height: 100px;
  background-color: red;
  position: relative;
  animation-name: example;
  animation-duration: 4s;
  animation-delay: 2s;
}

@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;}
}
</style>
</head>
<body>

<h1>CSS Animation</h1>

<p>The animation-delay property specifies a delay for the start of an animation. The following example has a 2 seconds delay before starting the animation:</p>

<div></div>

</body>
</html>


También se permiten valores negativos. Si se utilizan valores negativos, la animación comenzará como si ya hubiera estado reproduciéndose durante N segundos.

En el siguiente ejemplo, la animación comenzará como si ya hubiera sido jugando durante 2 segundos:

Ejemplo

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

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<head>
<style> 
div {
  width: 100px;
  height: 100px;
  background-color: red;
  position: relative;
  animation-name: example;
  animation-duration: 4s;
  animation-delay: -2s;
}

@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;}
}
</style>
</head>
<body>

<h1>CSS Animation</h1>

<p>Using negative values in the animation-delay property: Here, the animation will start as if it had already been playing for 2 seconds:</p>

<div></div>

</body>
</html>



Establecer cuántas veces debe ejecutarse una animación

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

El siguiente ejemplo ejecutará la animación 3 veces antes de que se detenga:

Ejemplo

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

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<head>
<style> 
div {
  width: 100px;
  height: 100px;
  background-color: red;
  position: relative;
  animation-name: example;
  animation-duration: 4s;
  animation-iteration-count: 3;
}

@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;}
}
</style>
</head>
<body>

<h1>CSS Animation</h1>

<p>The animation-iteration-count property specifies the number of times an animation should run. The following example will run the animation 3 times before it stops:</p>

<div></div>

</body>
</html>


El siguiente ejemplo utiliza el valor "infinito" para hacer la animación. continuar para siempre:

Ejemplo

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

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<head>
<style> 
div {
  width: 100px;
  height: 100px;
  background-color: red;
  position: relative;
  animation-name: example;
  animation-duration: 4s;
  animation-iteration-count: infinite;
}

@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;}
}
</style>
</head>
<body>

<h1>CSS Animation</h1>

<p>The animation-iteration-count property can be set to infinite to let the animation run for ever:</p>

<div></div>

</body>
</html>



Ejecutar animación en dirección inversa o ciclos alternos

La propiedad animation-direction especifica si una animación debe reproducirse hacia adelante, hacia atrás o alternativamente ciclos.

La propiedad dirección de animación puede tener los siguientes valores:

normal

- La animación se reproduce normalmente (hacia adelante). Esto es predeterminado

reverse

- La animación se reproduce en dirección inversa (al revé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 dirección inversa (hacia atrás):

Ejemplo

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

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<head>
<style> 
div {
  width: 100px;
  height: 100px;
  background-color: red;
  position: relative;
  animation-name: example;
  animation-duration: 4s;
  animation-direction: reverse;  
}

@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;}
}
</style>
</head>
<body>

<h1>CSS Animation</h1>

<p>The animation-direction property specifies whether an animation should be played forwards, backwards or in alternate cycles. The following example will run the animation in reverse direction (backwards):</p>

<div></div>

</body>
</html>


El siguiente ejemplo utiliza el valor "alternativo" para hacer la animación. Corre primero hacia adelante y luego hacia atrás:

Ejemplo

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

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<head>
<style> 
div {
  width: 100px;
  height: 100px;
  background-color: red;
  position: relative;
  animation-name: example;
  animation-duration: 4s;
  animation-iteration-count: 2;
  animation-direction: alternate;  
}

@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;}
}
</style>
</head>
<body>

<h1>CSS Animation</h1>

<p>The animation-direction property specifies whether an animation should be played forwards, backwards or in alternate cycles. The following example uses the value "alternate" to make the animation run forwards first, then backwards:</p>

<div></div>

</body>
</html>


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

Ejemplo

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

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<head>
<style> 
div {
  width: 100px;
  height: 100px;
  background-color: red;
  position: relative;
  animation-name: example;
  animation-duration: 4s;
  animation-iteration-count: 2;
  animation-direction: alternate-reverse;  
}

@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;}
}
</style>
</head>
<body>

<h1>CSS Animation</h1>

<p>The animation-direction property specifies whether an animation should be played forwards, backwards or in alternate cycles. The following example uses the value "alternate-reverse" to make the animation run backwards first, then forwards:</p>

<div></div>

</body>
</html>



Especificar la curva de velocidad de la animación.

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

La propiedad de función de sincronización de animación puede tener los siguientes valores:

ease

- Especifica una animación con un inicio lento, luego rápido y luego finalizado lentamente (esto es el valor predeterminado)

linear

- Especifica una animación con la misma velocidad de principio a fin.

ease-in

- Especifica una animación con un inicio lento.

ease-out

- Especifica una animación con un final lento.

ease-in-out

- Especifica una animación con un inicio y un final lentos.

cubic-bezier(n,n,n,n)

- Le permite definir sus propios valores en una función cúbica-bezier

El siguiente ejemplo muestra algunas de las diferentes curvas de velocidad que se pueden utilizar:

Ejemplo

#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;}

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<head>
<style> 
div {
  width: 100px;
  height: 50px;
  background-color: red;
  font-weight: bold;
  position: relative;
  animation: mymove 5s;
  animation-fill-mode: forwards;
}

#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;}

@keyframes mymove {
  from {left: 0px;}
  to {left: 300px;}
}
</style>
</head>
<body>

<h1>CSS Animation</h1>

<p>The animation-timing-function property specifies the speed curve of the animation. The following example shows some of the different speed curves that can be used:</p>

<div id="div1">linear</div>
<div id="div2">ease</div>
<div id="div3">ease-in</div>
<div id="div4">ease-out</div>
<div id="div5">ease-in-out</div>

</body>
</html>



Especificar el modo de relleno para una animación

Las animaciones CSS no afectan a un elemento antes de que se reproduzca el primer fotograma clave. o después de reproducir el último fotograma clave. La propiedad animación-relleno-modo puede anular este comportamiento.

La propiedad animation-fill-mode especifica un estilo para el elemento de destino cuando la animación no se está reproduciendo (antes de que comienza, después de que termina, o ambos).

La propiedad Animation-fill-mode puede tener los siguientes valores:

none

- Valor por defecto. La animación no aplicará ningún estilo al elemento antes o después de su ejecución.

forwards

- El elemento conservará los valores de estilo establecidos en el último fotograma clave (depende de la dirección de la animación y del recuento de iteraciones de la animación).

backwards

- El elemento obtendrá los valores de estilo establecidos por el primer fotograma clave (depende de la dirección de la animación) y los conservará durante el período de retraso de la animación.

both

- La animación seguirá las reglas tanto para adelante como para atrás, extendiendo las propiedades de la animación en ambas direcciones.

El siguiente ejemplo permite que el elemento <div> conserve los valores de estilo del último fotograma clave cuando finaliza la animación:

Ejemplo

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

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<head>
<style> 
div {
  width: 100px;
  height: 100px;
  background: red;
  position: relative;
  animation-name: example;
  animation-duration: 3s;  
  animation-fill-mode: forwards;
}

@keyframes example {
  from {top: 0px;}
  to {top: 200px; background-color: blue;}
}
</style>
</head>
<body>

<h1>CSS Animation</h1>

<p>Let the div element retain the style values set by the last keyframe when the animation ends:</p>

<div></div>

</body>
</html>


El siguiente ejemplo permite que el elemento <div> obtenga los valores de estilo establecidos por el primer fotograma clave antes de que comience la animación (durante el período de retraso de la animación):

Ejemplo

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

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<head>
<style> 
div {
  width: 100px;
  height: 100px;
  background: red;
  position: relative;
  animation-name: example;
  animation-duration: 3s;  
  animation-delay: 2s;
  animation-fill-mode: backwards;
}

@keyframes example {
  from {top: 0px; background-color: yellow;}
  to {top: 200px;}
}
</style>
</head>
<body>

<h1>CSS Animation</h1>

<p>Let the div element get the style values set by the first keyframe before the animation starts (during the animation-delay period):</p>

<div></div>

</body>
</html>


El siguiente ejemplo permite que el elemento <div> obtenga los valores de estilo establecidos por el primer fotograma clave antes de que comience la animación y conservar los valores de estilo desde el último fotograma clave cuando finaliza la animación:

Ejemplo

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

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<head>
<style> 
div {
  width: 100px;
  height: 100px;
  background: red;
  position: relative;
  animation-name: example;
  animation-duration: 3s;  
  animation-delay: 2s;
  animation-fill-mode: both;
}

@keyframes example {
  from {top: 0px; background-color: yellow;}
  to {top: 200px; background-color: blue;}
}
</style>
</head>
<body>

<h1>CSS Animation</h1>

<p>Let the div element get the style values set by the first keyframe before the animation starts, and retain the style values from the last keyframe when the animation ends:</p>

<div></div>

</body>
</html>



Propiedad taquigráfica de animación

El siguiente ejemplo utiliza seis de las propiedades de la animación:

Ejemplo

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

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<head>
<style> 
div {
  width: 100px;
  height: 100px;
  background-color: red;
  position: relative;
  animation-name: example;
  animation-duration: 5s;
  animation-timing-function: linear;
  animation-delay: 2s;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}

@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;}
}
</style>
</head>
<body>

<h1>CSS Animation</h1>

<p>This example uses six of the animation properties:</p>

<div></div>

</body>
</html>


El mismo efecto de animación que el anterior se puede lograr usando la taquigrafía Propiedad animación:

Ejemplo

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

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<head>
<style> 
div {
  width: 100px;
  height: 100px;
  background-color: red;
  position: relative;
  animation: myfirst 5s linear 2s infinite alternate;
}

@keyframes myfirst {
  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;}
}
</style>
</head>
<body>

<h1>CSS Animation</h1>

<p>This example uses the shorthand animation property:</p>

<div></div>

</body>
</html>




Propiedades de animación CSS

La siguiente tabla enumera la regla @keyframes y todas las propiedades de animación CSS:

@keyframes

Especifica el código de animación.

animation

Una propiedad abreviada para configurar todas las propiedades de la animación.

animation-delay

Especifica un retraso para el inicio de una animación.

animation-direction

Especifica si una animación debe reproducirse hacia adelante, hacia atrás o en ciclos alternos

animation-duration

Especifica cuánto tiempo debe tardar una animación en completar un ciclo.

animation-fill-mode

Especifica un estilo para el elemento cuando la animación no se está reproduciendo. (antes de que comience, después de que termine o ambos)

animation-iteration-count

Especifica el número de veces que se debe reproducir una animación.

animation-name

Especifica el nombre de la animación @keyframes.

animation-play-state

Especifica si la animación está en ejecución o en pausa.

animation-timing-function

Especifica la curva de velocidad de la animación.