Переходы. Переходы Transition css3 примеры

  • 29.06.2020

Internet Explorer пока не поддерживает свойство transition.

Firefox 4 требует приставки -moz-.

Chrome и Safari требуют приставки -webkit-.

Opera требует приставки -o-.

Как это работает?

CSS3 переходы - это эффекты, которые позволяют элементу плавно изменять один стиль на другой.

Чтобы сделать это, вы должны указать две вещи:

  • Указать свойство CSS, к которому вы хотите добавить эффект
  • Определить продолжительность эффекта.

Пример

Эффект перехода для свойства width, продолжительность: 2 секунды:

div
{
transition: width 2s;
-moz-transition: width 2s; /* Firefox 4 */
-webkit-transition: width 2s; /* Safari и Chrome */
-o-transition: width 2s; /* Opera */
}

Замечание: Если свойство duration не указано, плавный переход не произойдет, потому что значение по умолчанию равно 0.

Эффект начнется, когда указанное свойство CSS начнет изменяться. Обычно эффект перехода (плавного изменения CSS свойства) привязывают к моменту, когда пользователь перемещает мышь над элементом:

Пример

Указать:hover для элементов

:

Замечание: Когда курсор мыши уходит за пределы области элемента, он плавно изменяется обратно к своему исходному стилю.

Несколько Изменений

Чтобы добавить эффект более чем к одному стилю, укажите несколько свойств, разделяя их запятыми:

Пример

Добавление эффектов изменения ширины, высоты и трансформации:

Свойства Перехода

Следующая таблица перечисляет все свойства transition:

Свойство Описание CSS
transition Стенографическое (сокращенное) свойство для установки четырех свойств перехода в одном свойстве 3
transition-property Указывает название CSS свойства, к которому следует применить переход 3
transition-duration Определяет, сколько времени займет переход. Значение по умолчанию 0 3
transition-timing-function Описывает, как будет изменяться скорость выполнения перехода. Значение по умолчанию "ease" 3
transition-delay Определяет, когда начнется переход. По умолчанию равно 0 3

Два примера ниже устанавливает все свойства перехода:

Пример

Использование всех свойств перехода в одном примере:

div
{
transition-property: width;
transition-duration: 1s;
transition-timing-function: linear;
transition-delay: 2s;

Moz-transition-property:width;
-moz-transition-duration:1s;
-moz-transition-timing-function:linear;
-moz-transition-delay:2s;
/* Safari и Chrome */
-webkit-transition-property:width;
-webkit-transition-duration:1s;
-webkit-transition-timing-function:linear;
-webkit-transition-delay:2s;
/* Opera */
-o-transition-property:width;
-o-transition-duration:1s;
-o-transition-timing-function:linear;
-o-transition-delay:2s;
}

Дата добавления: 2011-10-16



Свойство transition относится к новым свойствам CSS3. Познакомимся с ним поближе.

Все мы привыкли, что при наведении мышкой изменяется цвет ссылки. При этом цвет меняется резко, без плавного перехода. Свойство transition позволит добавить небольшую анимацию при изменении цвета без использования JavaScript.

В спецификации к данному свойству говорится следующее:

CSS Transitions allow property changes in CSS values to occur smoothly over a specified duration.

Иными словами, CSS Transitions позволяют назначать изменения свойств CSS плавно и в течение некоторого времени.

Применять свойство transition можно к чему угодно - фону, цвету, длине, размеру шрифта и т.д. В основном это свойства, задающие цвет или свойства, которые могут быть выражены в единицах длины (px, em, ex) или в процентах. В качестве события мы так же можем использовать псевдоклассы:focus и:active.

Браузеры

Сразу скажу о браузерах - новый стандарт еще не принят, поэтому на данный момент необходимо использовать префиксы -webkit-, -moz- и -o-. Отсюда видно, что свойство поддерживают браузеры Chrome, Safari, Opera 10.5+, Firefox 4+. Наш "любимый" Internet Explorer как всегда не у дел, пользователь просто не увидит никакой анимации.

В этой статье я использовал префикс -webkit- , поэтому все приведенные здесь примеры будут работать только в Chrome и Safari.

Рассмотрим простой пример - добавим плавный переход фона ссылки

Для начала вспомним, как делается обычная смена цвета ссылки при наведении мышкой.

Теперь воспользуемся свойством CSS transition для плавной смены фона у ссылки. Создадим новый класс, который будет идентичен классу simple и добавим несколько новых строчек:

A.cool { padding: 5px 10px; background: #69f; color: #000; -webkit-transition-property: background; -webkit-transition-duration: 0.5s; -webkit-transition-timing-function: ease; } a.cool:hover { background: #33f; color: #fff; }

Создаем еще пару тестовых ссылок и посмотрим на результат:

Теперь наш фон плавно меняет цвет в течение полусекунды! Из примера видно, что мы добавили три новые строчки со свойствами -webkit-transition-property, -webkit-transition-duration, -webkit-transition-timing-function .

На самом деле, их можно объединить в одно свойство:

Webkit-transition: background 0.5s ease;

Также можно добавить плавное изменение цвета текста:

A.cool2 { padding: 5px 10px; background: #69f; color: #000; -webkit-transition: background 0.5s ease, color 1.0s ease; } a.cool2:hover { background: #33f; color: #fff; }

Данный код при наведении мышки будет плавно менять цвет фона в течение полусекунды и цвет шрифта в течение 1 секунды. Проверяем:

Если мы будем использовать одинаковые параметры для анимации, то можно использовать выражение: -webkit-transition: all 0.5s ease;

Теперь Transition-эффект будет применяться ко всем изменяющимся свойствам с одинаковыми параметрами - 0.5 секунд, ease-эффект.

Можно также добавить задержку для эффекта при помощи transition-delay :

A.cool3 { padding: 5px 10px; background: #69f; color: #000; -webkit-transition: all 0.5s ease; -webkit-transition-delay: 0.5s; } a.cool3:hover { background: #33f; color: #fff; }

Теперь анимация будет работать через полсекунды после наведения мышки. Проверим на всякий случай:

Справочная таблица

Чтобы лучше усвоить материал, предлагаю вашему вниманию небольшую справочную таблицу.

Transition-property Свойство, к которому применяем анимацию. Практически любое свойство CSS: color, background, width, font-size и т.д. transition-duration Длительность анимации. Время в секундах. transition-timing-function Временная функция, используемая для анимации: ease, linear, ease-in-out, ease-in, ease-out, cubic-bezier transition-delay Задержка анимации. Время в секундах.

CSS свойство transition позволяет задать все свойства эффекта перехода (переход между двумя состояниями элемента) в одном объявлении.

Это свойство является короткой записью для следующих свойств (список соответствует порядку указания значений):

Поддержка браузерами

Свойство
Opera

IExplorer

Edge
transition 26.0
4.0
-webkit-
16.0
4.0
-moz-
12.1
10.5
-o-
6.1
3.1
-webkit-
10.0 12.0

CSS синтаксис:

transition: "property duration timing-function delay | initial | inherit" ; /* допускается перечислять эффект перехода отдельно для каждого свойства в одном объявлении */ /* синтаксис будет следующим: property | duration | timing function | delay,..., property | duration | timing function | delay */ /* допускается указывать не все значения, при этом необходимо соблюдать порядок, указанный вверху примера */ /* учтите, что если вы хотите задать только delay, то вам придется указать и duration (0s) */ /* т.е. если вы хотите указать задержку 4 секунды, то вам необходимо записать это transition: 0s 4s; */ transition: width 2s ease 100ms, height 1s linear 2s, background 0s 4s; /* Смотри пример внизу страницы */

JavaScript синтаксис:

Object.style.transition = "width 3s ease-out 2s"

Значения свойства

Значение Описание
transition-property Указывает имя свойства CSS для которого используется переходный эффект. Значение по умолчанию all.
transition-duration Определяет, сколько секунд или миллисекунд эффект перехода занимает времени.
transition-timing-function Используется, чтобы описать, как рассчитываются промежуточные значения CSS свойства, которое находится под воздействием эффекта перехода, используя при этом математическую функцию (кубическую кривую Безье). Это, по сути, позволяет создать кривую "разгона", так что скорость перехода может меняться в течение длительности эффекта перехода. Значение по умолчанию ease.
transition-delay Указывает, когда эффект перехода начнется (выступает в роли задержки начала эффекта). Значение по умолчанию 0 секунд.
Устанавливает свойство в значение по умолчанию.
Указывает, что значение наследуется от родительского элемента.

Версия CSS

CSS3

Наследуется

Нет.

Анимируемое

Нет.

Пример использования

Пример использования универсального свойства transition в CSS
class = "test" > Свойство transition в CSS

Пример выдвигающегося поиска на CSS, используя селектор атрибута (с указанным значением) и универсальное свойство transition:

Выдвигающийся поиск на CSS Поиск:

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 a timing 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. As it doesn"t make sense to animate some properties, the list of animatable properties is limited to a finite set.

Note: The set of properties that can be animated is changing as the specification develops.

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:

(Note that these transitions loop infinitely only for the purpose of our examples; CSS transition s only visualize a property change from start to finish. If you need visualizations that loop, look into the CSS animation property.)

transition-property 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. transition-duration 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.

transition-duration: 0.5s

Lorem
.parent { width: 250px; height:125px;} .box { width: 100px; height: 100px; background-color: red; font-size: 20px; left: 0px; top: 0px; position:absolute; -webkit-transition-property: width height background-color font-size left top transform -webkit-transform color; -webkit-transition-duration: 0.5s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top transform -webkit-transform color; transition-duration: 0.5s; transition-timing-function: ease-in-out; } .box1{ transform: rotate(270deg); -webkit-transform: rotate(270deg); width: 50px; height: 50px; background-color: blue; color: yellow; font-size: 18px; left: 150px; top: 25px; position: absolute; -webkit-transition-property: width height background-color font-size left top transform -webkit-transform color; -webkit-transition-duration: 0.5s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top transform -webkit-transformv color; transition-duration: 0.5s; transition-timing-function: ease-in-out; } function updateTransition() { var el = document.querySelector("div.box"); if (el) { el.className = "box1"; } else { el = document.querySelector("div.box1"); el.className = "box"; } return el; } var intervalID = window.setInterval(updateTransition, 7000);

transition-duration: 1s

Lorem
.parent { width: 250px; height:125px;} .box { width: 100px; height: 100px; background-color: red; font-size: 20px; left: 0px; top: 0px; position: absolute; -webkit-transition-property: width height background-color font-size left top -webkit-transform color; -webkit-transition-duration: 1s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top transform color; transition-duration: 1s; transition-timing-function: ease-in-out; } .box1{ transform: rotate(270deg); -webkit-transform: rotate(270deg); width: 50px; height: 50px; background-color: blue; color: yellow; font-size: 18px; left: 150px; top: 25px; position: absolute; -webkit-transition-property: width height background-color font-size left top -webkit-transform transform color; -webkit-transition-duration: 1s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top transform -webkit-transform color; transition-duration: 1s; transition-timing-function: ease-in-out; } function updateTransition() { var el = document.querySelector("div.box"); if (el) { el.className = "box1"; } else { el = document.querySelector("div.box1"); el.className = "box"; } return el; } var intervalID = window.setInterval(updateTransition, 7000);

transition-duration: 2s

Lorem
.parent { width: 250px; height:125px;} .box { width: 100px; height: 100px; background-color: red; font-size: 20px; left: 0px; top: 0px; position: absolute; -webkit-transition-property: width height background-color font-size left top transform -webkit-transform color; -webkit-transition-duration: 2s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top transform -webkit-transform color; transition-duration: 2s; transition-timing-function: ease-in-out; } .box1{ transform: rotate(270deg); -webkit-transform: rotate(270deg); width: 50px; height: 50px; background-color: blue; color: yellow; font-size: 18px; left: 150px; top: 25px; position: absolute; -webkit-transition-property: width height background-color font-size left top transform -webkit-transform color; -webkit-transition-duration: 2s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top transform -webkit-transform color; transition-duration: 2s; transition-timing-function: ease-in-out; } function updateTransition() { var el = document.querySelector("div.box"); if (el) { el.className = "box1"; } else { el = document.querySelector("div.box1"); el.className = "box"; } return el; } var intervalID = window.setInterval(updateTransition, 7000);

transition-duration: 4s

Lorem
.parent { width: 250px; height:125px;} .box { width: 100px; height: 100px; background-color: red; font-size: 20px; left: 0px; top: 0px; position: absolute; -webkit-transition-property: width height background-color font-size left top transform -webkit-transform color; -webkit-transition-duration: 4s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top transform -webkit-transform color; transition-duration: 4s; transition-timing-function: ease-in-out; } .box1{ transform: rotate(270deg); -webkit-transform: rotate(270deg); width: 50px; height: 50px; background-color: blue; color: yellow; font-size: 18px; left: 150px; top: 25px; position: absolute; -webkit-transition-property: width height background-color font-size left top transform -webkit-transform color; -webkit-transition-duration: 4s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top transform -webkit-transform color; transition-duration: 4s; transition-timing-function: ease-in-out; } function updateTransition() { var el = document.querySelector("div.box"); if (el) { el.className = "box1"; } else { el = document.querySelector("div.box1"); el.className = "box"; } return el; } var intervalID = window.setInterval(updateTransition, 7000);

transition-timing-function Specifies a function to define how intermediate values for properties are computed. Timing functions determine how intermediate values of the transition are calculated. Most timing 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 .

transition-timing-function: ease

Lorem
.parent { width: 250px; height:125px;} .box { width: 100px; height: 100px; background-color: red; font-size: 20px; left: 0px; top: 0px; position: absolute; -webkit-transition-property: width height background-color font-size left top color; -webkit-transition-duration: 2s; -webkit-transition-timing-function: ease; transition-property: width height background-color font-size left top color; transition-duration: 2s; transition-timing-function: ease; } .box1{ width: 50px; height: 50px; background-color: blue; color: yellow; font-size: 18px; left: 150px; top: 25px; position:absolute; -webkit-transition-property: width height background-color font-size left top color; -webkit-transition-duration: 2s; -webkit-transition-timing-function: ease; transition-property: width height background-color font-size left top color; transition-duration: 2s; transition-timing-function: ease; } function updateTransition() { var el = document.querySelector("div.box"); if (el) { el.className = "box1"; } else { el = document.querySelector("div.box1"); el.className = "box"; } return el; } var intervalID = window.setInterval(updateTransition, 7000);

transition-timing-function: linear

Lorem
.parent { width: 250px; height:125px;} .box { width: 100px; height: 100px; background-color: red; font-size: 20px; left: 0px; top: 0px; position: absolute; -webkit-transition-property: width height background-color font-size left top color; -webkit-transition-duration: 2s; -webkit-transition-timing-function: linear; transition-property: width height background-color font-size left top color; transition-duration: 2s; transition-timing-function: linear; } .box1{ width: 50px; height: 50px; background-color: blue; color: yellow; font-size: 18px; left: 150px; top:25px; position: absolute; -webkit-transition-property: width height background-color font-size left top color; -webkit-transition-duration: 2s; -webkit-transition-timing-function: linear; transition-property: width height background-color font-size left top color; transition-duration: 2s; transition-timing-function: linear; } function updateTransition() { var el = document.querySelector("div.box"); if (el) { el.className = "box1"; } else { el = document.querySelector("div.box1"); el.className = "box"; } return el; } var intervalID = window.setInterval(updateTransition, 7000);

transition-timing-function: step-end

Lorem
.parent { width: 250px; height:125px;} .box { width: 100px; height: 100px; background-color: red; font-size: 20px; left: 0px; top: 0px; position: absolute; -webkit-transition-property: width height background-color font-size left top color; -webkit-transition-duration: 2s; -webkit-transition-timing-function: step-end; transition-property: width height background-color font-size left top color; transition-duration: 2s; transition-timing-function: step-end; } .box1{ width: 50px; height: 50px; background-color: blue; color: yellow; font-size: 18px; left: 150px; top:25px; position: absolute; -webkit-transition-property: width height background-color font-size left top color; -webkit-transition-duration: 2s; -webkit-transition-timing-function: step-end; transition-property: width height background-color font-size left top color; transition-duration: 2s; transition-timing-function: step-end; } function updateTransition() { var el = document.querySelector("div.box"); if (el) { el.className = "box1"; } else { el = document.querySelector("div.box1"); el.className = "box"; } return el; } var intervalID = window.setInterval(updateTransition, 7000);

transition-timing-function: steps(4, end)

Lorem
.parent { width: 250px; height:125px;} .box { width: 100px; height: 100px; background-color: red; font-size: 20px; left: 0px; top: 0px; position: absolute; -webkit-transition-property: width height background-color font-size left top color; -webkit-transition-duration: 2s; -webkit-transition-timing-function: steps(4, end); transition-property: width height background-color font-size left top color; transition-duration: 2s; transition-timing-function: steps(4, end); } .box1{ width: 50px; height: 50px; background-color: blue; color: yellow; font-size: 18px; left: 150px; top: 25px; position: absolute; -webkit-transition-property: width height background-color font-size left top color; -webkit-transition-duration: 2s; -webkit-transition-timing-function: steps(4, end); transition-property: width height background-color font-size left top color; transition-duration: 2s; transition-timing-function: steps(4, end); } function updateTransition() { var el = document.querySelector("div.box"); if (el) { el.className = "box1"; } else { el = document.querySelector("div.box1"); el.className = "box"; } return el; } var intervalID = window.setInterval(updateTransition, 7000);

transition-delay Defines how long to wait between the time a property is changed and the transition actually begins.

transition-delay: 0.5s

Lorem
.parent { width: 250px; height: 125px; } .box { width: 100px; height: 100px; background-color: red; font-size: 20px; left: 0px; top: 0px; position: absolute; -webkit-transition-property: width height background-color font-size left top color; -webkit-transition-duration: 2s; -webkit-transition-delay: 0.5s; -webkit-transition-timing-function: linear; transition-property: width height background-color font-size left top color; transition-duration: 2s; transition-delay: 0.5s; transition-timing-function: linear; } .box1 { width: 50px; height: 50px; background-color: blue; color: yellow; font-size: 18px; left: 150px; top:25px; position: absolute; -webkit-transition-property: width height background-color font-size left top color; -webkit-transition-duration: 2s; -webkit-transition-delay: 0.5s; -webkit-transition-timing-function: linear; transition-property: width height background-color font-size left top color; transition-duration: 2s; transition-delay: 0.5s; transition-timing-function: linear; } function updateTransition() { var el = document.querySelector("div.box"); if (el) { el.className = "box1"; } else { el = document.querySelector("div.box1"); el.className = "box"; } return el; } var intervalID = window.setInterval(updateTransition, 7000);

transition-delay: 1s

Lorem
.parent { width: 250px; height: 125px; } .box { width: 100px; height: 100px; background-color: red; font-size: 20px; left: 0px; top: 0px; position: absolute; -webkit-transition-property: width height background-color font-size left top color; -webkit-transition-duration: 2s; -webkit-transition-delay: 1s; -webkit-transition-timing-function: linear; transition-property: width height background-color font-size left top color; transition-duration: 2s; transition-delay: 1s; transition-timing-function: linear; } .box1{ width: 50px; height: 50px; background-color: blue; color: yellow; font-size: 18px; left: 150px; top: 25px; position: absolute; -webkit-transition-property: width height background-color font-size left top color; -webkit-transition-duration: 2s; -webkit-transition-delay: 1s; -webkit-transition-timing-function: linear; transition-property: width height background-color font-size left top color; transition-duration: 2s; transition-delay: 1s; transition-timing-function: linear; } function updateTransition() { var el = document.querySelector("div.box"); if (el) { el.className = "box1"; } else { el = document.querySelector("div.box1"); el.className = "box"; } return el; } var intervalID = window.setInterval(updateTransition, 7000);

transition-delay: 2s

Lorem
.parent { width: 250px; height: 125px; } .box { width: 100px; height: 100px; background-color: red; font-size: 20px; left: 0px; top: 0px; position: absolute; -webkit-transition-property: width height background-color font-size left top color; -webkit-transition-duration: 2s; -webkit-transition-delay: 2s; -webkit-transition-timing-function: linear; transition-property: width height background-color font-size left top color; transition-duration: 2s; transition-delay: 2s; transition-timing-function: linear; } .box1 { width: 50px; height: 50px; background-color: blue; color: yellow; font-size: 18px; left: 150px; top: 25px; position: absolute; -webkit-transition-property: width height background-color font-size left top color; -webkit-transition-duration: 2s; -webkit-transition-delay: 2s; -webkit-transition-timing-function: linear; transition-property: width height background-color font-size left top color; transition-duration: 2s; transition-delay: 2s; transition-timing-function: linear; } function updateTransition() { var el = document.querySelector("div.box"); if (el) { el.className = "box1"; } else { el = document.querySelector("div.box1"); el.className = "box"; } return el; } var intervalID = window.setInterval(updateTransition, 7000);

transition-delay: 4s

Lorem
.parent { width: 250px; height: 125px; } .box { width: 100px; height: 100px; background-color: red; font-size: 20px; left: 0px; top: 0px; position: absolute; -webkit-transition-property: width height background-color font-size left top color; -webkit-transition-duration: 2s; -webkit-transition-delay: 4s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top color; transition-duration: 2s; transition-delay: 4s; transition-timing-function: ease-in-out; } .box1 { width: 50px; height: 50px; background-color: blue; color: yellow; font-size: 18px; left: 150px; top: 25px; position: absolute; -webkit-transition-property: width height background-color font-size left top color; -webkit-transition-duration: 2s; -webkit-transition-delay: 4s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top color; transition-duration: 2s; transition-delay: 4s; transition-timing-function: ease-in-out; } function updateTransition() { var el = document.querySelector("div.box"); if (el) { el.className = "box1"; } else { el = document.querySelector("div.box1"); el.className = "box"; } return el; } var intervalID = window.setInterval(updateTransition, 7000);

The 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

HTML Content

The box below combines transitions for: width, height, background-color, transform. Hover over the box to see these properties animated.

Sample

CSS Content

.box { border-style: solid; border-width: 1px; display: block; width: 100px; height: 100px; background-color: #0000FF; transition: width 2s, height 2s, background-color 2s, transform 2s; } .box:hover { background-color: #FFCCCC; width: 200px; height: 200px; transform: 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.

Before we look at code snippets, you might want to take a look at the live demo (assuming your browser supports transitions).

First, we set up the menu using HTML:

Then we build the CSS to implement the look and feel of our menu. The relevant portions are shown here:

A { color: #fff; background-color: #333; transition: all 1s ease-out; } a:hover, a:focus { color: #333; background-color: #fff; }

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

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 window.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.

Click anywhere to move the ball

Using JavaScript you can make the effect of moving the ball to a certain position happen:

Var f = document.getElementById("foo"); document.addEventListener("click", function(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. Simply add a transition to the element and any change will happen smoothly:

P { padding-left: 60px; } #foo { border-radius: 50px; width: 50px; height: 50px; background: #c00; position: absolute; top: 0; left: 0; transition: transform 1s; }

Detecting the start and completion of a transition

propertyName A string indicating the name of the CSS property whose transition completed. elapsedTime 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 .

Свойство CSS Transition нужен для установки анимационного перехода из одного состояния в другое. Анимация работает с помощью псевдоэлементов :hover и :active , т.е. при переходе объекта из одного состояния в другое.

Синтаксис CSS transition

transition : [ none | ] || || || ;

Синтаксис выглядит довольно устрошающе, но по факту все просто. Давайте разберем на простых примерах как это работает. После двух примеров будут разобраны все каждого из элемента синтаксиса:

Примеры со свойством Transition

Пример #1. Анимация в html через transition

Разберем этот пример более более подробно. Свойство transition: all 1s linear отвечает за плавный переход. Если его не писать, то был бы резкий переход. Чтобы вы понимали разницу, ниже представлен пример без анимационного эффекта:

Код transition: all 1s linear означает следующее:

Чтобы все остальные объекты не смещались из-за увеличивающегося квадрата, можно использовать свойство свойство transform .

Пример #2. Увеличение объекта в html без смещения других объектов

На странице преобразуется в следующее

Теперь объект увеличивается и не происходит смещения других объектов.

Рассмотрим детально какие значения может принимать каждый из параметров

Значения свойств transition

1. Параметр transition-property

Свойство transition-property отвечает за части свойств объекта, к которым будет применена анимация. Может принимать следующие значения

  • all - ко всему объекту (можно опустить, если задано время)
  • color - к цвету текста
  • background - к цвету фона объекта
  • width , height - к изменению габаритов по ширине и высоте соответственно
  • none - анимация отсутствует (по умолчанию стоит у каждого элемента)

Для включения нескольких свойств, их можно перечислить через запятую.

2. Параметр transition-duration

Определяет количество времени в течении которого длится трансформация. Измеряется в секунда (s) и милисекундах (ms).

Например

Параметр transition-duration можно задавать отдельным свойством в CSS:

transition-duration : 1s ;

3. Параметр transition-timing-function

Это важнейший параметр, который определяет как изменяется скорость трансформации. Например, в начале с замедленинем, или же в конце.

Синтаксис transition-timing-function
transition-timing-function : value ;

Где value может принимать значения:

  • ease (значение по умолчанию) - замедление во время старта и финиша, равносильно параметру cubic-bezier(0.25, 0.1, 0.25, 1.0)
  • linear - равномерная скорость на протяжении всей трансформации, равносильно параметру cubic-bezier(0.0, 0.0, 1.0, 1.0)
  • ease-in - замедление в начале, равносильно параметру cubic-bezier(0.42, 0, 1.0, 1.0)
  • ease-out - замедление в конце, равносильно параметру cubic-bezier(0, 0, 0.58, 1.0)
  • ease-in-out - замедление при старте и в конце (похож на ease, но с другими коэффициентами скорости), равносильно параметру cubic-bezier(0.42, 0, 0.58, 1.0)
  • step-start - мгновенный старт, равносильно параметру steps(1, start)
  • step-end - мгновенное исполнение в конце, равносильно параметру steps(1, end)
  • cubic-bezier(a1,b1,a2,b2) - задание собственного изменения скорости
  • steps(a,b) - изменение рывками

Например

4. Параметр transition-delay

Задает время задержки до начала эффекта перехода. Измеряется в секундах (s) и милисекундах (ms)

Например

Пример #3. Разные задержки

Ранее мы уже говорили про возможность задавать разные задержки для трансформаций. Рассмотрим это на примере.

На странице преобразуется в следующее

Пример сложной трансформации с задержками

Браузеры

Не все браузеры поддерживают трансформацию. Необходимо использовать вендорные префиксы CSS :

  • -ms-transform-origin - для IE9 и старше (младше девятой версии трансформация не поддерживается
  • -webkit-transform-origin - для Chrome, Safari, Android и iOS
  • -o-transform-origin - для Opera до версии 12.10
  • -moz-transform-origin - для Firefox до версии 16.0

Для обращения из JavaScript к свойству CSS transition используется следующая конструкция:

document.getElementById("elementID").style.transition