Css animation one direction

animation

This property is a shorthand for the following CSS properties:

Syntax

/* @keyframes duration | easing-function | delay | iteration-count | direction | fill-mode | play-state | name */ animation: 3s ease-in 1s 2 reverse both paused slidein; /* @keyframes duration | easing-function | delay | name */ animation: 3s linear 1s slidein; /* two animations */ animation: 3s linear slidein, 3s ease-out 5s slideout; 

The animation property is specified as one or more single animations, separated by commas.

Each individual animation is specified as:

Note: animation-timeline , animation-range-start , and animation-range-end are not currently included in this list, as current implementations are reset-only. This means that including animation resets a previously-declared animation-timeline value to auto and previously-declared animation-range-start and animation-range-end values to normal , but these properties cannot be set via animation . When creating CSS scroll-driven animations, you need to declare these properties after declaring any animation shorthand for it to take effect.

Values

Determines the type of transition. The value must be one of those available in .

The number of times the animation is played. The value must be one of those available in animation-iteration-count .

The direction in which the animation is played. The value must be one of those available in animation-direction .

Determines how styles should be applied to the animation’s target before and after its execution. The value must be one of those available in animation-fill-mode .

Читайте также:  Php telegram bot conversation

Determines whether the animation is playing or not. The value must be one of those available in animation-play-state .

Description

The order of time values within each animation definition is important: the first value that can be parsed as a is assigned to the animation-duration , and the second one is assigned to animation-delay .

The order of other values within each animation definition is also important for distinguishing an animation-name value from other values. If a value in the animation shorthand can be parsed as a value for an animation property other than animation-name , then the value will be applied to that property first and not to animation-name . For this reason, the recommended practice is to specify a value for animation-name as the last value in a list of values when using the animation shorthand; this holds true even when you specify multiple, comma-separated animations using the animation shorthand.

While an animation name must be set for an animation to be applied, all values of the animation shorthand are optional, and default to the initial value for each long-hand animation component. The initial value of animation-name is none , meaning if no animation-name value is declared in the animation shorthand property, there is no animation to apply on any of the properties.

When the animation-duration value is omitted from the animation shorthand property, the value for this property defaults to 0s . In this case, the animation will still occur (the animationStart and animationEnd events will be fired) but no animation will be visible.

Accessibility concerns

Blinking and flashing animation can be problematic for people with cognitive concerns such as Attention Deficit Hyperactivity Disorder (ADHD). Additionally, certain kinds of motion can be a trigger for Vestibular disorders, epilepsy, and migraine and Scotopic sensitivity.

Consider providing a mechanism for pausing or disabling animation as well as using the Reduced Motion Media Query to create a complimentary experience for users who have expressed a preference for reduced animated experiences.

Formal definition

  • animation-name : none
  • animation-duration : 0s
  • animation-timing-function : ease
  • animation-delay : 0s
  • animation-iteration-count : 1
  • animation-direction : normal
  • animation-fill-mode : none
  • animation-play-state : running
  • animation-timeline : auto
  • animation-name : as specified
  • animation-duration : as specified
  • animation-timing-function : as specified
  • animation-delay : as specified
  • animation-direction : as specified
  • animation-iteration-count : as specified
  • animation-fill-mode : as specified
  • animation-play-state : as specified
  • animation-timeline : a list, each item either a case-sensitive CSS identifier or the keywords none , auto

Formal syntax

animation =
#

=
||
||
||
||
||
||
||
[ none | ]

=
linear |
|
|

=
infinite |

=
normal |
reverse |
alternate |
alternate-reverse

=
none |
forwards |
backwards |
both

=
running |
paused

=
|

=
linear( )

=
ease |
ease-in |
ease-out |
ease-in-out |
cubic-bezier( , , , )

=
step-start |
step-end |
steps( [, ]? )

=
[ ]#

=
jump-start |
jump-end |
jump-none |
jump-both |
start |
end

=
&&
?

=

Examples

Note: Animating CSS Box Model properties is discouraged. Animating any box model property is inherently CPU intensive; consider animating the transform property instead.

Sun Rise

Here we animate a yellow sun across a light blue sky. The sun rises to the center of the viewport and then falls out of sight.

:root  overflow: hidden; /* hides any part of the sun below the horizon */ background-color: lightblue; display: flex; justify-content: center; /* centers the sun in the background */ > .sun  background-color: yellow; border-radius: 50%; /* creates a circular background */ height: 100vh; /* makes the sun the size of the viewport */ aspect-ratio: 1 / 1; animation: 4s linear 0s infinite alternate sun-rise; > @keyframes sun-rise  from  /* pushes the sun down past the viewport */ transform: translateY(110vh); > to  /* returns the sun to its default position */ transform: translateY(0); > > 

Animating Multiple Properties

Adding onto the sun animation in the previous example, we add a second animation changing the color of the sun as it rises and sets. The sun starts off dark red when it is below the horizon and changes to a bright orange as it reaches the top.

:root  overflow: hidden; background-color: lightblue; display: flex; justify-content: center; > .sun  background-color: yellow; border-radius: 50%; height: 100vh; aspect-ratio: 1 / 1; animation: 4s linear 0s infinite alternate animating-multiple-properties; > /* it is possible to animate multiple properties in a single animation */ @keyframes animating-multiple-properties  from  transform: translateY(110vh); background-color: red; filter: brightness(75%); > to  transform: translateY(0); background-color: orange; /* unset properties i.e. 'filter' will revert to default values */ > > 

Applying Multiple Animations

Here is a sun that rises and falls on a lightblue background. The sun gradually rotates through a rainbow of colors. The timing of the sun’s position and color are independent.

:root  overflow: hidden; background-color: lightblue; display: flex; justify-content: center; > .sun  background-color: yellow; border-radius: 50%; height: 100vh; aspect-ratio: 1 / 1; /* multiple animations are separated by commas, each animation's parameters are set independently */ animation: 4s linear 0s infinite alternate rise, 24s linear 0s infinite psychedelic; > @keyframes rise  from  transform: translateY(110vh); > to  transform: translateY(0); > > @keyframes psychedelic  from  filter: hue-rotate(0deg); > to  filter: hue-rotate(360deg); > > 

Cascading Multiple Animations

Here is a yellow sun on a lightblue background. The sun bounces between the left and right sides of the viewport. The sun remains in the viewport even though a rise animation is defined. The rise animation’s transform property is ‘overwritten’ by the bounce animation.

:root  overflow: hidden; background-color: lightblue; display: flex; justify-content: center; > .sun  background-color: yellow; border-radius: 50%; height: 100vh; aspect-ratio: 1 / 1; /* animations declared later in the cascade will override the properties of previously declared animations */ /* bounce 'overwrites' the transform set by rise, hence the sun only moves horizontally */ animation: 4s linear 0s infinite alternate rise, 4s linear 0s infinite alternate bounce; > @keyframes rise  from  transform: translateY(110vh); > to  transform: translateY(0); > > @keyframes bounce  from  transform: translateX(-50vw); > to  transform: translateX(50vw); > > 

See Using CSS animations for additional examples.

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Jul 7, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

animation — direction

Решаем, в каком направлении будет проигрываться анимация.

Время чтения: меньше 5 мин

Обновлено 20 декабря 2021

Кратко

Скопировать ссылку «Кратко» Скопировано

Свойство animation — direction сообщает браузеру, должна ли анимация проигрываться в обратном порядке.

Пример

Скопировать ссылку «Пример» Скопировано

 .element  animation-name: circle-to-square; animation-duration: 2s; animation-iteration-count: infinite; animation-direction: alternate;> .element  animation-name: circle-to-square; animation-duration: 2s; animation-iteration-count: infinite; animation-direction: alternate; >      

Как пишется

Скопировать ссылку «Как пишется» Скопировано

  • normal — значение по умолчанию, анимация воспроизводится от начала до конца, после чего возвращается к начальному кадру.
  • reverse — анимация проигрывается в обратном порядке, от последнего ключевого кадра до первого, после чего возвращается к последнему кадру.
  • alternate — каждый нечётный повтор (первый, третий, пятый) анимации воспроизводится в прямом порядке, а каждый чётный повтор (второй, четвёртый, шестой) анимации воспроизводится в обратном порядке.
  • alternate — reverse — аналогично значению alternate , но чётные и нечётные повторы меняются местами.

Подсказки

Скопировать ссылку «Подсказки» Скопировано

Подробнее об анимациях написано в статье «CSS-анимации».

Источник

Свойство animation-direction

Свойство animation-direction задает направление анимации. По умолчанию анимация повторится только 1 раз и затем вернется в исходное состояние, затем, если задана задержка animation-delay , будет ждать заданное время и потом цикл начнется сначала.

Данное свойство позволяет поменять это поведение, например, так чтобы анимация после окончания оставалась в том месте, где она закончилась, а не перескакивала в начальное положение.

Также можно задать такое поведение: анимация дойдет до крайней точки и вернется обратно (как в transition ). Смотрите описание ниже.

Синтаксис

Значения

Значение Описание
reverse Анимация будет проигрываться в обратном направлении.
alternate Анимация будет проигрываться сначала в прямом, а потом в обратном направлении (как transition).
alternate-reverse Анимация будет проигрываться из конечного положения в начальное и обратно. По сути это значения alternate и reverse в одном флаконе.
normal Анимация будет проигрываться от начала к концу, а после окончания скачком перескакивать в начальное положение.

Значение по умолчанию: normal .

Пример

Сейчас элемент будет двигаться в одну сторону, а потом возвращаться обратно, так как задано значение alternate . При этом animation-duration имеет значение 3 секунды и это значит, что перемещения «туда» и «обратно» будут длиться по 3 секунды:

Пример

Сейчас элемент будет двигаться в обратную сторону (должен слева направо, а будет справа налево):

Пример

Сейчас элемент будет двигаться туда-сюда, но в обратном направлении (должен начинать слева, а будет начинать справа):

Смотрите также

  • свойство animation-name ,
    которое задает имя анимации
  • свойство animation-duration ,
    которое задает продолжительность анимации
  • свойство animation-delay ,
    которое задает задержку перед выполнением анимации
  • свойство animation-timing-function ,
    которое задает скорость выполнения анимации
  • свойство animation-iteration-count ,
    которое задает количество итераций анимации
  • свойство animation-fill-mode ,
    которое задает состояние анимации
  • свойство animation-play-state ,
    которое позволяет поставить анимацию на паузу
  • свойство animation ,
    представляющее собой сокращение для анимаций
  • команду @keyframes ,
    задающую ключевые кадры анимации
  • плавные переходы transition , представляющие собой анимацию по наведению на элемент

Источник

Оцените статью