Propriedade CSS animation
Conheça a propriedade CSS animation, utilizada para animar (alterar gradualmente de um estilo para outro) propriedades CSS com valores discretos. Veja os exemplos.
A propriedade animation é utilizada para animar (alterar gradualmente de um estilo para outro) propriedades CSS com valores contínuos: propriedades de layout (border, height, width, etc.), propriedades que definem a posição (left, top), tamanhos de letra, cores e opacidades.
A propriedade animation é uma das propriedades CSS3.
Os browsers mais antigos podem exigir o prefixo -webkit- para suporte de versões anteriores.
As propriedades que utilizam uma palavra-chave como valor, tais como display: none; ou visibility: hidden;, não podem ser animadas. As propriedades com valores como height: auto; também não podem ser animadas.
A at-rule @keyframes
Para utilizar uma animação, deve primeiro especificar o que deve acontecer em momentos específicos durante a animação. Isto é definido com a at-rule @keyframes.
A regra @keyframes é composta pela palavra-chave "@keyframes" seguida de animation-name, que identifica a animação. A animação é depois aplicada a um elemento utilizando este identificador como valor da propriedade animation-name.
Entre chavetas, colocamos os seletores de keyframe, que definem os keyframes (ou pontos de referência) na sequência da animação onde os estilos devem mudar. O seletor de keyframe pode começar com uma percentagem (%) ou com as palavras-chave "from" (igual a 0%) e "to" (igual a 100%). 0% é o ponto de partida da animação e 100% é o ponto final.
Exemplo de animação com a regra @keyframe:
Exemplo da propriedade animation com @keyframes
<!DOCTYPE html>
<html>
<head>
<style>
.element {
padding: 50px;
animation: pulse 4s infinite;
}
@keyframes pulse {
0% {
background-color: #8ebf42;
}
50% {
background-color: #1c87c9;
}
100% {
background-color: #d5dce8;
}
}
</style>
</head>
<body>
<div class="element">Background of this text is animated using CSS3 animation property.</div>
</body>
</html>Neste exemplo, associamos a animação ao elemento <div>. A animação durará 4 segundos e mudará gradualmente a cor de fundo do elemento <div> de "verde" para "cinzento".
Propriedades relacionadas com animação
animation é a propriedade abreviada (shorthand) utilizada para definir todas as propriedades da animação numa única declaração. Listamos em baixo todas as propriedades padrão relacionadas com animação.
Vejamos agora as propriedades relacionadas com animação em ação.
Exemplo de animação com algumas propriedades relacionadas com animação:
@keyframes pulse {
/* declare animation actions here */
}
.element {
animation-name: pulse;
animation-duration: 3.5s;
animation-timing-function: ease-in;
animation-delay: 1s;
animation-direction: alternate;
animation-iteration-count: infinite;
animation-fill-mode: none;
animation-play-state: running;
}
/*
The same can be declared using the animation shorthand property
*/
.element {
animation: pulse 3.5s ease-in 1s alternate infinite none running;
}Animation-name
Esta propriedade define o nome da regra @keyframes que pretende aplicar.
Sintaxe da propriedade animation-name
animation-name: keyframe-name | none | initial | inheritExemplo da propriedade animation-name:
<!DOCTYPE html>
<html>
<head>
<style>
div {
padding: 50px;
animation: element 4s infinite;
}
@keyframes element {
0% {
background-color: #8ebf42;
}
50% {
background-color: #1c87c9;
}
100% {
background-color: #d5dce8;
}
}
</style>
</head>
<body>
<h2>Animation-name example</h2>
<div>The name of the animation is set as "element".</div>
</body>
</html>Animation-duration
Define a duração (em segundos ou milissegundos) que a animação demora a completar um ciclo. Se esta propriedade não for especificada, a animação não ocorrerá.
Sintaxe da propriedade animation-duration
animation-duration: time | initial | inheritExemplo da propriedade animation-duration:
<!DOCTYPE html>
<html>
<head>
<style>
.element {
padding: 50px;
animation: pulse 7s infinite;
}
@keyframes pulse {
0% {
background-color: #8ebf42;
}
50% {
background-color: #1c87c9;
}
100% {
background-color: #eee
}
}
</style>
</head>
<body>
<div class="element">Background of this text is animated using CSS3 animation property</div>
</body>
</html>Animation-timing-function
Esta propriedade define como uma animação irá progredir ao longo da duração de cada ciclo — e não ao longo de toda a animação.
Sintaxe da propriedade animation-timing-function
animation-timing-function: linear | ease | ease-in | ease-out | ease-in-out | cubic-bezier(n,n,n,n) | initial | inheritExemplo da propriedade animation-timing-function com o valor "ease":
<!DOCTYPE html>
<html>
<head>
<title>The title of the document</title>
<style>
div {
width: 100px;
height: 100px;
border-radius: 50%;
background: #1c87c9;
position: relative;
-webkit-animation: element 5s infinite;
/* Safari 4.0 - 8.0 */
-webkit-animation-timing-function: ease;
/* Safari 4.0 - 8.0 */
animation: element 5s infinite;
animation-timing-function: ease;
}
/* Safari 4.0 - 8.0 */
@-webkit-keyframes element {
from {
left: 0px;
}
to {
left: 200px;
}
}
@keyframes element {
from {
left: 0px;
}
to {
left: 200px;
}
}
</style>
</head>
<body>
<h2>Animation-timing-function example</h2>
<div></div>
</body>
</html>Animation-delay
Esta propriedade define o tempo (em segundos ou milissegundos) entre o carregamento do elemento e o início da animação.
Sintaxe da propriedade animation-delay
animation-delay: time | initial | inheritExemplo da propriedade animation-delay:
Exemplo da propriedade CSS animation-delay
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 120px;
height: 120px;
background: #1c87c9;
position: relative;
animation: delay 5s infinite;
animation-delay: 3s;
}
@keyframes delay {
from {
left: 0px;
}
to {
left: 300px;
}
}
</style>
</head>
<body>
<h2>Animation-delay example</h2>
<p>Here the animation starts after 3 seconds.</p>
<div></div>
</body>
</html>Animation-direction
Define se a animação deve ser reproduzida ao contrário nos ciclos alternados ou não.
Sintaxe da propriedade animation-direction
animation-direction: normal | reverse | alternate | alternate-reverse | initial | inheritPodem ser aplicados os seguintes valores:
- normal — (predefinição) a animação é reproduzida para a frente (keyframes de 0% a 100%)
- reverse — a animação é reproduzida para trás (keyframes de 100% a 0%)
- alternate — a animação é reproduzida para a frente, depois é invertida e repetida.
- alternate-reverse — a animação é reproduzida para trás e depois para a frente.
Exemplo da propriedade animation-direction:
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 120px;
height: 120px;
background: #ccc;
position: relative;
animation: myfirst 5s 1;
animation-direction: normal;
}
@keyframes myfirst {
0% {
background: #8DC3CF;
left: 0px;
top: 0px;
}
25% {
background: #1c87c9;
left: 200px;
top: 0px;
}
50% {
background: #030E10;
left: 200px;
top: 200px;
}
75% {
background: #666;
left: 0px;
top: 200px;
}
100% {
background: #8ebf42;
left: 0px;
top: 0px;
}
}
</style>
</head>
<body>
<h2>Animation-direction example</h2>
<p>Here the animation plays forwards.</p>
<div></div>
</body>
</html>Animation-iteration-count
Define o número de vezes que um ciclo de animação deve ser reproduzido antes de parar. O valor predefinido é um, mas pode ser definido qualquer valor inteiro positivo. Se definir a palavra-chave infinite, a animação será reproduzida indefinidamente.
Um número inteiro igual a zero ou negativo nunca reproduzirá a animação.
Sintaxe da propriedade animation-iteration-count
animation-iteration-count: number | infinite | initial | inheritExemplo da propriedade animation-iteration-count:
Exemplo da propriedade CSS <span class="property">animation-iteration-count</span>:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
html,
body {
margin: 0;
padding: 0;
}
div {
position: relative;
width: 100px;
height: 100px;
margin: 30px 0;
border-radius: 50%;
animation-name: pulse;
}
.element-one {
background-color: #1c87c9;
animation-duration: 3s;
animation-iteration-count: 3;
}
.element-two {
margin: 0;
background-color: #83bf42;
animation-duration: 5s;
animation-iteration-count: 2;
}
@keyframes pulse {
0% {
left: 0;
}
50% {
left: 50%;
}
100% {
left: 0;
}
}
</style>
</head>
<body>
<h2>The animation-iteration-count example</h2>
<p>The animation-iteration-count sets the number of times an animation cycle should be played before stopping.</p>
<div class="element-one"></div>
<div class="element-two"></div>
</body>
</html>Animation-fill-mode
Esta propriedade especifica um estilo a aplicar ao elemento antes ou depois da execução da animação.
Sintaxe da propriedade animation-fill-mode
animation-fill-mode: none | forwards | backwards | both | initial | inheritPode assumir os seguintes valores:
- forwards - especifica que o elemento deve manter os valores de estilo definidos pelo último keyframe (depende das propriedades animation-iteration-count e animation-direction).
- backwards - especifica que o elemento deve assumir os valores de estilo definidos pelo primeiro keyframe (depende de animation-direction) e mantê-los durante o período de animation-delay.
- both - especifica que a animação deve seguir as regras tanto de forwards como de backwards.
- none - (predefinição) especifica que não será aplicado qualquer estilo ao elemento antes ou depois da execução da animação
Exemplo da propriedade animation-fill-mode com o valor "forwards":
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 100px;
height: 100px;
background: #1c87c9;
position: relative;
-webkit-animation: element 5s;
/* Safari 4.0 - 8.0 */
-webkit-animation-fill-mode: forwards;
/* Safari 4.0 - 8.0 */
animation: element 5s;
animation-fill-mode: forwards;
}
/* Safari 4.0 - 8.0 */
@-webkit-keyframes element {
from {
top: 0px;
}
to {
top: 200px;
background-color: blue;
}
}
@keyframes element {
from {
top: 0px;
}
to {
top: 200px;
background-color: #8ebf42;
}
}
</style>
</head>
<body>
<h2>Animation-fill-mode example</h2>
<div></div>
</body>
</html>Animation-play-state
Esta propriedade especifica se a animação está a ser reproduzida ou em pausa.
Sintaxe da propriedade animation-play-state
animation-play-state: paused | running | initial | inheritO valor predefinido é running.
Exemplo da propriedade animation-play-state com o valor "running":
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 150px;
height: 150px;
background: #ccc;
position: relative;
animation: play 10s;
animation-play-state: running;
}
@keyframes play {
from {
left: 0px;
}
to {
left: 200px;
}
}
</style>
</head>
<body>
<h2>Animation-play-state example</h2>
<p>Here the animation-play-state is set to "running".</p>
<div></div>
</body>
</html>Animações múltiplas
É possível declarar várias animações num seletor; basta separar os valores com vírgulas.
Exemplo de várias animações num seletor:
Exemplo da propriedade animation com animações múltiplas
<!DOCTYPE html>
<html>
<head>
<style>
html,
body {
height: 100%;
margin: 0;
}
body {
display: flex;
align-items: center;
justify-content: center;
}
.element {
height: 200px;
width: 200px;
background-color: #1c87c9;
animation: pulse 5s ease infinite alternate, nudge 5s linear infinite alternate;
}
@keyframes pulse {
0%,
100% {
background-color: #8ebf42;
}
50% {
background-color: #1c87c9;
}
}
@keyframes nudge {
0%,
100% {
transform: translate(0, 0);
}
50% {
transform: translate(150px, 0);
}
80% {
transform: translate(-150px, 0);
}
}
</style>
</head>
<body>
<div class="element"></div>
</body>
</html>