- transition
- Constituent properties
- Syntax
- Formal definition
- Formal syntax
- Examples
- Simple example
- HTML
- CSS
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- transition
- Пример
- Подробно
- Как записывается
- Как понять
- Подсказки
- Особенности
- Css transition opacity ease
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
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:
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-delay : as specified
- transition-duration : as specified
- transition-property : as specified
- transition-timing-function : 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
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 18, 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.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; >
.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 , то скрытие и появление не будет плавным.
Css transition opacity ease
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 weekLike/Subscribe us for latest updates or newsletter