- CSS animation-iteration-count Property
- Browser Support
- CSS Syntax
- Property Values
- More Examples
- Example
- Related Pages
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- CSS-анимации
- Кратко
- animation — delay
- animation — play — state
- animation — fill — mode
- animation
- Несколько анимаций
- animation-iteration-count
- Try it
- Syntax
- Values
- Formal definition
- Formal syntax
CSS animation-iteration-count Property
The animation-iteration-count property specifies the number of times an animation should be played.
Default value: | 1 |
---|---|
Inherited: | no |
Animatable: | no. Read about animatable |
Version: | CSS3 |
JavaScript syntax: | object.style.animationIterationCount=»infinite» Try it |
Browser Support
The numbers in the table specify the first browser version that fully supports the property.
Numbers followed by -webkit-, -moz-, or -o- specify the first version that worked with a prefix.
CSS Syntax
Property Values
Value | Description | Demo |
---|---|---|
number | A number that defines how many times an animation should be played. Default value is 1 | Play it » |
infinite | Specifies that the animation should be played infinite times (for ever) | Play it » |
initial | Sets this property to its default value. Read about initial | |
inherit | Inherits this property from its parent element. Read about inherit |
More Examples
Example
Play the animation forever:
Related Pages
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
CSS-анимации
Большой набор свойств для создания настоящих живых анимаций.
- Кратко
- @keyframes
- animation-name
- animation-duration
- animation-iteration-count
- animation-direction
- animation-timing-function
- linear
- ease
- ease-in
- ease-out
- ease-in-out
- cubic-bezier(x1, y1, x2, y2)
- step-start
- step-end
- steps(количество шагов, положение шага)
Обновлено 24 октября 2022
Кратко
Скопировать ссылку «Кратко» Скопировано
Веб в процессе развития из текста с картинками превратился в интерактивное пространство. Заходя на разные сайты, вы постоянно видите анимации. От микроскопических реакций на наведение курсора до сложных сцен.
Вернёмся к нашему розовому кругу и укажем, что он должен превращаться в синий квадрат нелинейно, медленно разгоняясь к концу анимации.
.child-one animation-name: circle-to-square; animation-duration: 5s; animation-iteration-count: infinite; animation-direction: alternate; animation-timing-function: ease-in;>
.child-one animation-name: circle-to-square; animation-duration: 5s; animation-iteration-count: infinite; animation-direction: alternate; animation-timing-function: ease-in; >
Анимация стала более естественной, не такой компьютерной.
Пришло время заняться правой фигурой и превратить синий квадрат в розовый круг. Используем практически те же самые свойства, что и для круга, только зададим другое значение для свойства animation — direction , чтобы шаги анимации воспроизводились в обратном порядке:
.child-two animation-name: circle-to-square; animation-duration: 5s; animation-iteration-count: infinite; animation-direction: alternate-reverse; animation-timing-function: ease-in;>
.child-two animation-name: circle-to-square; animation-duration: 5s; animation-iteration-count: infinite; animation-direction: alternate-reverse; animation-timing-function: ease-in; >
Сейчас обе фигуры меняются синхронно. Добавим правой фигуре небольшую задержку.
animation — delay
Скопировать ссылку «animation-delay» Скопировано
Свойство задаёт задержку воспроизведения анимации. Значением может быть любое число, как отрицательное, так и положительное.
Если значение положительное, то будет задержка перед началом анимации. Если значение отрицательное, то анимация начнётся как бы за кадром.
Пусть анимация правого элемента начнётся с задержкой -2.5 секунды. Так она будет начинаться с середины:
.child-two animation-name: circle-to-square; animation-duration: 5s; animation-iteration-count: infinite; animation-direction: alternate-reverse; animation-timing-function: ease-in; animation-delay: -2.5s;>
.child-two animation-name: circle-to-square; animation-duration: 5s; animation-iteration-count: infinite; animation-direction: alternate-reverse; animation-timing-function: ease-in; animation-delay: -2.5s; >
animation — play — state
Скопировать ссылку «animation-play-state» Скопировано
Свойство, позволяющее ставить анимацию на паузу и запускать снова.
- running — анимация проигрывается (значение по умолчанию).
- paused — анимация ставится на паузу. При повторном запуске анимации она продолжается с того места, где была остановлена.
Добавим возможность взаимодействовать с нашей анимацией. Пусть по наведению курсора анимация ставится на паузу, а если курсор убран, то продолжает проигрываться.
.child:hover animation-play-state: paused;>
.child:hover animation-play-state: paused; >
animation — fill — mode
Скопировать ссылку «animation-fill-mode» Скопировано
Последнее свойство анимации — animation — fill — mode — сообщает браузеру, нужно ли применять стили ключевых кадров до или после проигрывания анимации.
- none — стили анимации не применяются до и после проигрывания анимации (значение по умолчанию).
- forwards — после окончания анимации элемент сохранит стили последнего ключевого кадра.
- backwards — после окончания анимации к элементу будут применены стили первого ключевого кадра.
- both — до начала анимации к элементу применяется первый ключевой кадр, а после окончания анимации элемент останется в состоянии последнего ключевого кадра.
Для лучшего понимания работы этих значений посмотрите демо 👇
animation
Скопировать ссылку «animation» Скопировано
animation — это мега-шорткат, в котором можно за раз указать значения для всех перечисленных выше свойств, начинающихся на animation — .
Значения указываются через пробел. Порядок указания значений не важен. Из-за того, что значения этих свойств очень разные, браузер сам догадывается, какое значение к какому свойству относится. Важно только помнить, что первое значение времени будет воспринято как значение animation — duration (длительность анимации), а второе — animation — delay (задержка воспроизведения).
Для работы анимации совсем не обязательно перечислять все значения. Достаточно указать имя анимации и её длительность. Для остальных свойств будут установлены значения по умолчанию.
.child-two animation: circle-to-square 2s infinite alternate-reverse ease-in 1s;>
.child-two animation: circle-to-square 2s infinite alternate-reverse ease-in 1s; >
Несколько анимаций
Скопировать ссылку «Несколько анимаций» Скопировано
Есть возможность применить к одному элементу сразу несколько анимаций. Для этого нужно перечислить несколько значений через запятую. Возможно указать любое количество значений для любого из свойств анимации. Анимации будут воспроизводиться одновременно.
Например, разобьём предыдущую анимацию на две отдельные. Одна будет отвечать за изменение формы элемента, а вторая за изменение цвета.
@keyframes circle-to-square from width: 50px; height: 50px; > 50% width: 100%; height: 50px; > to width: 100%; height: 100%; >> @keyframes color-change from background-color: #F498AD; > 50% background-color: #7F6EDB; > to background-color: #2E9AFF; >>
@keyframes circle-to-square from width: 50px; height: 50px; > 50% width: 100%; height: 50px; > to width: 100%; height: 100%; > > @keyframes color-change from background-color: #F498AD; > 50% background-color: #7F6EDB; > to background-color: #2E9AFF; > >
И присвоим обе анимации одному элементу, при этом задав первой задержку, и указав разное время воспроизведения.
.child animation: circle-to-square 10s infinite alternate ease-out 1s, color-change 5s alternate linear infinite;>
.child animation: circle-to-square 10s infinite alternate ease-out 1s, color-change 5s alternate linear infinite; >
В итоге форма меняется за 10 секунд, а цвет перетекает из розового в синий за 5 секунд. А потом обратно. Очень красиво и медитативно 🙌
animation-iteration-count
The animation-iteration-count CSS property sets the number of times an animation sequence should be played before stopping.
Try it
It is often convenient to use the shorthand property animation to set all animation properties at once.
Syntax
/* Keyword value */ animation-iteration-count: infinite; /* values */ animation-iteration-count: 3; animation-iteration-count: 2.4; /* Multiple values */ animation-iteration-count: 2, 0, infinite; /* Global values */ animation-iteration-count: inherit; animation-iteration-count: initial; animation-iteration-count: revert; animation-iteration-count: revert-layer; animation-iteration-count: unset;
The animation-iteration-count property is specified as one or more comma-separated values.
Values
The animation will repeat forever.
The number of times the animation will repeat; this is 1 by default. You may specify non-integer values to play part of an animation cycle: for example, 0.5 will play half of the animation cycle. Negative values are invalid.
Note: When you specify multiple comma-separated values on an animation-* property, they are applied to the animations in the order in which the animation-name s appear. For situations where the number of animations and animation-* property values do not match, see Setting multiple animation property values.
Note: When creating CSS scroll-driven animations, specifying an animation-iteration-count causes the animation to repeat that number of times over the course of the timeline’s progression. If an animation-iteration-count is not provided, the animation will only occur once. infinite is a valid value for scroll-driven animations, but it results in an animation that doesn’t work.
Formal definition
Formal syntax