transition
Transitions enable you to define the transition between two states of an element. Different states may be defined using pseudo-classes like :hover or :active or dynamically set using JavaScript.
Constituent properties
This property is a shorthand for the following CSS properties:
- transition-delay
- transition-duration
- transition-property
- transition-timing-function
Syntax
/* Apply to 1 property */ /* property name | duration */ transition: margin-right 4s; /* property name | duration | delay */ transition: margin-right 4s 1s; /* property name | duration | easing function */ transition: margin-right 4s ease-in-out; /* property name | duration | easing function | delay */ transition: margin-right 4s ease-in-out 1s; /* Apply to 2 properties */ transition: margin-right 4s, color 1s; /* Apply to all changed properties */ transition: all 0.5s ease-out; /* Global values */ transition: inherit; transition: initial; transition: revert; transition: revert-layer; transition: unset;
The transition property is specified as one or more single-property transitions, separated by commas.
Each single-property transition describes the transition that should be applied to a single property (or the special values all and none ). It includes:
- zero or one value representing the property to which the transition should apply. This may be any one of:
- the keyword none
- the keyword all
- a naming a CSS property.
See how things are handled when lists of property values aren’t the same length. In short, extra transition descriptions beyond the number of properties actually being animated are ignored.
Formal definition
- transition-delay : 0s
- transition-duration : 0s
- transition-property : all
- transition-timing-function : ease
- transition-behavior : normal
- transition-delay : as specified
- transition-duration : as specified
- transition-property : as specified
- transition-timing-function : as specified
- transition-behavior : as specified
Formal syntax
transition =
#=
[ none | ] ||
||
||=
all |=
linear |
|
|
=
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
Simple example
In this example, when the user hovers over the element, there is a one-second delay before the four-second font-size transition occurs.
HTML
a class="target">Hover over mea>
CSS
.target font-size: 14px; transition: font-size 4s 1s; > .target:hover font-size: 36px; >There are several more examples of CSS transitions included in the Using CSS transitions article.
Specifications
Specification CSS Transitions
# transition-shorthand-propertyBrowser compatibility
BCD tables only load in the browser
See also
- Using CSS transitions
- TransitionEvent
Found a content problem with this page?
- Edit the page on GitHub.
- Report the content issue.
- View the source on GitHub.
This page was last modified on Jul 18, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
- Product help
- Report an issue
Our communities
Developers
- Web Technologies
- Learn Web Development
- MDN Plus
- Hacks Blog
- Website Privacy Notice
- Cookies
- Legal
- Community Participation Guidelines
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.Using CSS transitions
CSS transitions provide a way to control animation speed when changing CSS properties. Instead of having property changes take effect immediately, you can cause the changes in a property to take place over a period of time. For example, if you change the color of an element from white to black, usually the change is instantaneous. With CSS transitions enabled, changes occur at time intervals that follow an acceleration curve, all of which can be customized.
Animations that involve transitioning between two states are often called implicit transitions as the states in between the start and final states are implicitly defined by the browser.
CSS transitions let you decide which properties to animate (by listing them explicitly), when the animation will start (by setting a delay), how long the transition will last (by setting a duration), and how the transition will run (by defining an easing function, e.g., linearly or quick at the beginning, slow at the end).
Which CSS properties can be transitioned?
The Web author can define which property has to be animated and in which way. This allows the creation of complex transitions. However, some properties are not animatable as it doesn’t make sense to animate them.
Note: The auto value is often a very complex case. The specification recommends not animating from and to auto . Some user agents, like those based on Gecko, implement this requirement and others, like those based on WebKit, are less strict. Using animations with auto may lead to unpredictable results, depending on the browser and its version, and should be avoided.
Defining transitions
CSS Transitions are controlled using the shorthand transition property. This is the best way to configure transitions, as it makes it easier to avoid out of sync parameters, which can be very frustrating to have to spend lots of time debugging in CSS.
You can control the individual components of the transition with the following sub-properties:
Specifies the name or names of the CSS properties to which transitions should be applied. Only properties listed here are animated during transitions; changes to all other properties occur instantaneously as usual.
Specifies the duration over which transitions should occur. You can specify a single duration that applies to all properties during the transition, or multiple values to allow each property to transition over a different period of time.
Specifies a function to define how intermediate values for properties are computed. Easing functions determine how intermediate values of the transition are calculated. Most easing functions can be specified by providing the graph of the corresponding function, as defined by four points defining a cubic bezier. You can also choose easing from Easing functions cheat sheet.
Defines how long to wait between the time a property is changed and the transition actually begins.
The transition shorthand CSS syntax is written as follows:
div transition: ; >Examples
Simple example
This example performs a four-second font size transition with a two-second delay between the time the user mouses over the element and the beginning of the animation effect:
#delay font-size: 14px; transition-property: font-size; transition-duration: 4s; transition-delay: 2s; > #delay:hover font-size: 36px; >Multiple animated properties example
body> p> The box below combines transitions for: width, height, background-color, rotate. Hover over the box to see these properties animated. p> div class="box">Samplediv> body>
CSS
.box border-style: solid; border-width: 1px; display: block; width: 100px; height: 100px; background-color: #0000ff; transition: width 2s, height 2s, background-color 2s, rotate 2s; > .box:hover background-color: #ffcccc; width: 200px; height: 200px; rotate: 180deg; >When property value lists are of different lengths
If any property’s list of values is shorter than the others, its values are repeated to make them match. For example:
div transition-property: opacity, left, top, height; transition-duration: 3s, 5s; >This is treated as if it were:
div transition-property: opacity, left, top, height; transition-duration: 3s, 5s, 3s, 5s; >Similarly, if any property’s value list is longer than that for transition-property , it’s truncated, so if you have the following CSS:
div transition-property: opacity, left; transition-duration: 3s, 5s, 2s, 1s; >This gets interpreted as:
div transition-property: opacity, left; transition-duration: 3s, 5s; >Using transitions when highlighting menus
A common use of CSS is to highlight items in a menu as the user hovers the mouse cursor over them. It’s easy to use transitions to make the effect even more attractive.
First, we set up the menu using HTML:
nav> a href="#">Homea> a href="#">Abouta> a href="#">Contact Usa> a href="#">Linksa> nav>
Then we build the CSS to implement the look and feel of our menu:
nav display: flex; gap: 0.5rem; > a flex: 1; background-color: #333; color: #fff; border: 1px solid; padding: 0.5rem; text-align: center; text-decoration: none; transition: all 0.5s ease-out; > a:hover, a:focus background-color: #fff; color: #333; >This CSS establishes the look of the menu, with the background and text colors both changing when the element is in its :hover and :focus states:
JavaScript examples
Note: Care should be taken when using a transition immediately after:
- adding the element to the DOM using .appendChild()
- removing an element’s display: none; property.
This is treated as if the initial state had never occurred and the element was always in its final state. The easy way to overcome this limitation is to apply a setTimeout() of a handful of milliseconds before changing the CSS property you intend to transition to.
Using transitions to make JavaScript functionality smooth
Transitions are a great tool to make things look much smoother without having to do anything to your JavaScript functionality. Take the following example.
p>Click anywhere to move the ballp> div id="foo" class="ball">div>
Using JavaScript you can make the effect of moving the ball to a certain position happen:
const f = document.getElementById("foo"); document.addEventListener( "click", (ev) => f.style.transform = `translateY($ev.clientY - 25>px)`; f.style.transform += `translateX($ev.clientX - 25>px)`; >, false, );
With CSS you can make it smooth without any extra effort. Add a transition to the element and any change will happen smoothly:
.ball border-radius: 25px; width: 50px; height: 50px; background: #c00; position: absolute; top: 0; left: 0; transition: transform 1s; >Detecting the start and completion of a transition
You can use the transitionend event to detect that an animation has finished running. This is a TransitionEvent object, which has two added properties beyond a typical Event object:
A string indicating the name of the CSS property whose transition completed.
A float indicating the number of seconds the transition had been running at the time the event fired. This value isn’t affected by the value of transition-delay .
As usual, you can use the addEventListener() method to monitor for this event:
.addEventListener("transitionend", updateTransition, true);
You detect the beginning of a transition using transitionrun (fires before any delay) and transitionstart (fires after any delay), in the same kind of fashion:
.addEventListener("transitionrun", signalStart, true); el.addEventListener("transitionstart", signalStart, true);
Note: The transitionend event doesn’t fire if the transition is aborted before the transition is completed because either the element is made display : none or the animating property’s value is changed.
Specifications
Specification CSS Transitions See also
- The TransitionEvent interface and the transitionend event
- Using CSS animations
Found a content problem with this page?
- Edit the page on GitHub.
- Report the content issue.
- View the source on GitHub.
This page was last modified on Jul 7, 2023 by MDN contributors.
Your blueprint for a better internet.
CSS3 transition: плавные переходы
Переходы в CSS — это именно то, что помогает «вдохнуть жизнь» в неподвижную и скучную веб-страницу и анимировать ее. Смена одних CSS-стилей другими через заданный промежуток времени и с определенной скоростью — это и есть задача свойства transition .
Например, вы можете задавать скорость перехода от обычного стиля элемента к стилю в состоянии наведенного курсора, который задается через уже знакомый нам псевдокласс :hover . Если вы проходили практику в первой части книги, то, наверное, помните, что мы уже применяли кое-где свойство transition для плавной смены цвета ссылок и прозрачности.
Рекомендуем взглянуть на примеры CSS-переходов в нашей отдельной статье.
Как создать переход transition
Чтобы реализовать переход в CSS, необходимо записать два стиля для элемента — начальный и конечный. Также к начальному стилю дописывается свойство transition с необходимыми настройками для осуществления перехода. И, наконец, чтобы воспроизвести переход, понадобится «спусковой крючок», который запустит анимацию. Самый простой пример такого «спускового крючка» — это псевдокласс :hover . В этом случае переход от начального стиля к конечному будет происходить при наведении курсора на элемент. При снятии курсора с элемента конечный стиль будет преобразован обратно в начальный.
С какими стилями срабатывает transition
Во-первых, анимированию поддаются все трансформации ( scale() , rotate() , skew() и т. д.). Во-вторых, можно создавать переходы между значениями таких свойств, как color , background , width , height , opacity и т. д. Весь перечень можно посмотреть на сайте W3.org.
Кроссбраузерность
Свойство transition понимают следующие версии браузеров:
- IE 10+;
- Edge 12+;
- Firefox 5–15 (с префиксом -moz- ), Firefox 16+ (без префикса);
- Chrome 4–25 (с префиксом -webkit- ), Chrome 26+ (без префикса);
- Safari 5.1–6 (с префиксом -webkit- ), Safari 6.1+ (без префикса);
- Opera 12.1+.
Мобильные браузеры также хорошо поддерживают данное свойство (оно не работает лишь в Opera Mini). Ранние версии таких мобильных браузеров, как iOS Safari и Android Browser, распознают свойство transition при указании префикса -webkit- .
Для наилучшего обеспечения кроссбраузерности рекомендуется добавлять вендорные префиксы при использовании свойства transition.
Из каких свойств состоит transition
Свойство transition является универсальным: в нем можно записать значения для четырех отдельных свойств сразу. Эти свойства мы будем рассматривать по отдельности. Вот их список:
- transition-property — указывает, для какого стиля будет действовать переход;
- transition-duration — определяет длительность анимации;
- transition-timing-function — скорость хода анимации;
- transition-delay — время ожидания перед началом перехода.
На следующей странице мы разберем первое свойство из списка — transition-property.
transition
Свойство transition используется, когда нам нужно плавно изменить CSS-свойства между двумя состояниями элемента. Например, при наведении мышкой.
Пример
Скопировать ссылку «Пример» Скопировано
Подробно
Скопировать ссылку «Подробно» Скопировано
Свойство transition это шорткат. Как, например, margin или background . Оно включает в себя несколько подсвойств:
- transition — property — указываем свойство, которое хотим плавно изменить;
- transition — duration — длительность перехода;
- transition — timing — function — функция, описывающая скорость изменения свойства;
- transition — delay — задержка перед началом изменения.
Как записывается
Скопировать ссылку «Как записывается» Скопировано
Применить к одному свойству:
- Порядок записи: имя свойства | длительность:
.selector transition: transform 4s;>.selector transition: transform 4s; >- Порядок записи: имя свойства | длительность | задержка:
.selector transition: transform 4s 1s;>.selector transition: transform 4s 1s; >- Порядок записи: имя свойства | длительность | временная функция | задержка:
.selector transition: transform 4s ease-in-out 1s;>.selector transition: transform 4s ease-in-out 1s; >Применить к двум свойствам:
.selector transition: transform 4s, color 1s;>.selector transition: transform 4s, color 1s; >Применить ко всем свойствам, которые будут меняться:
.selector transition: all 0.5s ease-out;>.selector transition: all 0.5s ease-out; >Как понять
Скопировать ссылку «Как понять» Скопировано
Предположим, у нас есть кнопка, у которой мы хотим изменить фон при наведении мышкой.
button class="button">Кнопкаbutton>Тогда можно сказать, что у кнопки есть два состояния:
- Базовое состояние, когда мышка не над кнопкой.
- Состояние при наведении курсора мыши (ховер-состояние).
Стили для двух этих состояний могут быть записаны в CSS вот так
Стили для базового состояния:
.button background-color: blue;>.button background-color: blue; >Стили для ховер-состояния:
.button:hover background-color: white;>.button:hover background-color: white; >Чтобы при наведении фон кнопки изменялся не скачком, а плавно, мы используем свойство transition для плавного изменения цвета фона.
Стили для базового состояния:
.button background-color: blue; transition: background-color 0.6s;>.button background-color: blue; transition: background-color 0.6s; >Стили для ховер-состояния:
.button:hover background-color: white;>.button:hover background-color: white; >Если мы хотим плавно изменить два и более свойств, нужно просто перечислить их через запятую.
Стили для базового состояния:
.button background-color: pink; transition: background-color 0.6s, transform 0.5s;>.button background-color: pink; transition: background-color 0.6s, transform 0.5s; >Стили для ховер-состояния:
.button:hover background-color: white; transform: scale(110%);>.button:hover background-color: white; transform: scale(110%); >Не забывай о том, что вместе с изменяемым свойством обязательно должна указываться длительность изменения ( .5s ).
Подсказки
Скопировать ссылку «Подсказки» Скопировано
Обратите внимание, что свойство transition мы задали в стилях для базового состояния. Таким образом, мы заранее говорим браузеру, какое свойство должно изменяться плавно.
С помощью transition можно плавно изменять любое свойство, у которого значение записывается с помощью чисел (например, margin ). Исключения: visibility , z — index .
По возможности старайтесь не использовать слово all для описания перехода ( transition : all . 3s ). Да, это проще на первоначальном этапе, но позже из-за этого в какой-то момент могут начать плавно изменяться свойства, которые не должны этого делать. Ну и вообще, когда браузер встречает слово all , он начинает перебирать каждое свойство элемента в поисках необходимого. Это ненужная нагрузка.
Старайтесь использовать для анимации в первую очередь свойства transform и opacity — они самые производительные, потому что не приводят к перезапуску процессов Layout и Paint. Изменяйте свойства left , top , inset , margin , padding , width , inline — size , height , block — size и прочие с осторожностью, только когда без этого никак не обойтись.
Особенности
Скопировать ссылку «Особенности» Скопировано
Вторым состоянием необязательно должно быть состояние при наведении. Это может быть состояние :focus , :active , :checked или, например, появление дополнительного класса.
Мы можем настроить transition таким образом, что при изменении состояния переход будет выполняться с одной скоростью, а при обратном изменении состояния — с другой.
Стили для базового состояния:
.button background-color: pink; transition: background-color 0.3s, transform 0.2s;>.button background-color: pink; transition: background-color 0.3s, transform 0.2s; >Стили для hover-состояния:
.button:hover background-color: white; transform: scale(110%); transition: background-color 3s, transform 2.5s;>.button:hover background-color: white; transform: scale(110%); transition: background-color 3s, transform 2.5s; >Обратите внимание, в этом случае свойство transition задаётся для обоих состояний.
Длительность перехода может задаваться в секундах ( 0 . 3s ) или в миллисекундах ( 300ms ). Ноль перед точкой можно не писать ( .3s ).
Значение свойства z — index записывается числом, но его нельзя плавно изменить никаким способом.
Значение свойства visibility записывается строкой, но его в связке с opacity можно плавно изменять при помощи transition .
Кроме использования для изменения внешнего вида элемента, transition прекрасно подходит для решения задач с появлением элементов. Например, при реализации тултипов или всплывающих меню:
Fade in
Наведи на меняЭта подсказка проявиласьSlide up
Наведи на меняЭто подсказка, которая всплылаdiv> h2>Fade inh2> div class="tooltip-cnt"> span class="tooltip-target">Наведи на меняspan> div class="tooltip">Эта подсказка проявиласьdiv> div> div> div class="transitioned"> h2>Slide uph2> div class="tooltip-cnt"> span class="tooltip-target">Наведи на меняspan> div class="tooltip">Это подсказка, которая всплылаdiv> div> div>.tooltip-cnt position: relative;> .tooltip position: absolute; /* Описываем переход */ transition: opacity 0.4s, visibility 0.4s, transform 0.4s; /* Прячем элемент */ opacity: 0; visibility: hidden;> .transitioned .tooltip /* Второй тултип еще опускаем вниз */ transform: translateY(20px);> .tooltip-target:hover + .tooltip opacity: 1; visibility: visible;> .transitioned .tooltip-target:hover + .tooltip /* Поднимаем второй тултип обратно вверх при появлении */ transform: translateY(0);>.tooltip-cnt position: relative; > .tooltip position: absolute; /* Описываем переход */ transition: opacity 0.4s, visibility 0.4s, transform 0.4s; /* Прячем элемент */ opacity: 0; visibility: hidden; > .transitioned .tooltip /* Второй тултип еще опускаем вниз */ transform: translateY(20px); > .tooltip-target:hover + .tooltip opacity: 1; visibility: visible; > .transitioned .tooltip-target:hover + .tooltip /* Поднимаем второй тултип обратно вверх при появлении */ transform: translateY(0); >Обратите внимание, что мы прописали visibility как одно из свойств, которое нужно плавно изменить. Это работает в связке с opacity и обеспечивает возможность плавного появления и скрытия элемента:
.tooltip transition: opacity 0.4s, visibility 0.4s;>.tooltip transition: opacity 0.4s, visibility 0.4s; >Если использовать только opacity , то элемент станет невидимым, но будет доступен для взаимодействия с мышкой и клавиатурой.
Если использовать только visibility , то скрытие и появление не будет плавным.
