Static Template

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>      

Тогда можно сказать, что у кнопки есть два состояния:

  1. Базовое состояние, когда мышка не над кнопкой.
  2. Состояние при наведении курсора мыши (ховер-состояние).

Стили для двух этих состояний могут быть записаны в 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 Examples – How to Use Hover Animation, Change Opacity, and More

Said Hayani

Said Hayani

CSS Transition Examples – How to Use Hover Animation, Change Opacity, and More

If you are working with web technologies like CSS, HTML, and JavaScript, it’s important to have some basic knowledge about CSS animations and transitions.

In this article we are going to learn how to make some basic transition animations using CSS.

This is a simple transition that can be triggered when we hover over the element. We can add more than one transition that will run at the same time.

Let’s add a scale transform property to add scale transition to the element.

But the transition doesn’t seem to be smooth, because we didn’t define the duration of the transition or use any timing function.

If we add the transition property, it will make the element move more smoothly.

Let’s break down how the transition property works:

We can add more options like below (examples from the MDN):

  • transition-property: the property you want to animate. It can be any CSS element like background , height , translateY , translateX , and so on.
  • transition-duration: the duration of the transition
  • transition-delay: the delay before the transition starts

You can learn more about the different uses of transition in CSS here.

How to make transitions more interactive using the animation property and keyframes

We can do more with CSS transitions to make this animation more creative and interactive.

How to move an element with Keyframes

Let’s look at an example where the element moves from point A to point B. We will be using translateX and translateY.

         

This time we used new properties like animation and keyframes. We used the animation property to define the animation name and duration, and keyframes let us describe how the element should move.

 animation: moveToRight 2s ease-in-out;

Here I named the animation moveToRight – but you can use any name you like. The duration is 2s , and ease-in-out is a timing function.

There are other timing functions you can use like ease-in , linear , ease-out which basically make the animation smoother. You can learn more about the timing functions here.

@keyframes takes the name of the animation. In this case it’s moveToRight .

 @keyframes moveToRight < 0% < transform: translateX(0px); >100% < transform: translateX(300px); >>

keyframes will execute the animation in multiples steps. The example above uses a percentage to represent the range or the order of the transitions. We could also use the from and to methods. like below»

from represents the starting point or the first step of the animation.

to is the end point or the last step of the animation to be executed.

You may want to use a percentage in some cases. For example, say you want to add more than two transitions that will be executed in a sequence, like the following:

 @keyframes moveToRight < 0% < transform: translateX(0px); >50% < transform: translateX(150px); >100% < transform: translateX(300px); >>

We can be more creative and animate many properties at the same time like in the following example:

You can play around with properties and animation techniques in the sandbox here:

They are plenty more things we can do with keyframes. First, let’s add more transitions to our animation.

How to animate more properties and include them in the transition

This time we will animate the background, and we will make the element move in a square pattern. We’ll make the animation run forever using the infinite property as a timing function.

          

Let’s break it down. First we add infinite to make the animation run forever.

animation: moveToLeft 5s linear infinite;

And then we split the animation into four steps. At each step, we’ll run a different transition and all the animation will run in a sequence.

  • First step: set the element horizontally to translateX(0px) , and change the background to the gradient.
  • The second animation will move the element from the left to the right and change the background color.
  • The third animation will move the element down using translateY and change the background color again.
  • In the fourth step, the element will move back to the left and change the background color.
  • In the fifth animation the element should go back to its original place.

Wrapping up

In this article, we covered various things you can do with CSS transitions. You can use CSS transitions in many ways in your applications to create a better user experience.

After learning the basic of CSS animations you may want to go beyond and make more complex things that require user interaction. For this you can use JavaScript or any third party animation libraries out there.

Hi, my name is Said Hayani I created subscribi.io to help creators, bloggers and influencers to grow their audience through newsletter.

Источник

Читайте также:  Convert html to picture
Оцените статью