transform

Как работает transform в CSS на примерах

CSS свойство transform позволяет манипулировать элементами на вашей веб-странице, изменяя их форму, размер и положение.

В общем виде свойство transform записывается так: transform: функция(значение); , где функция — это тип преобразования, который вы хотите применить, а значение — параметры этого преобразования.

Свойство transform может принимать следующие значения:

  • none — никакого преобразования не применяется.
  • rotate(angle) — вращает элемент на заданный угол.
  • scale(x,y) — масштабирует элемент по осям X и Y.
  • translate(x,y) — перемещает элемент на заданные координаты.
  • skew(x-angle,y-angle) — наклоняет элемент на заданные углы по осям X и Y.

Есть некоторые другие варианты преобразований, например, на основе матриц — смотрите их в спецификации. Но они для математиков всяких 🙂

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

Вращение элемента — rotate

Свойство rotate вращает элемент вокруг его центра.

В этом примере элемент повернётся на 20 градусов по часовой стрелке (оси вы не увидите).

Читайте также:  Css content img position

Масштабирование элемента — scale

Свойство scale изменяет размер элемента.

Обратите внимание, при масштабировании изменяются все параметры элемента — например, рамка становится в полтора раза толще.

Перемещение элемента — translate

Свойство translate позволяет вам перемещать элемент по экрану.

Наклон элемента — skew

Свойство skew позволяет вам наклонять элемент по осям X и Y — как если бы вы нажимали на его углы.

Анимация превращений

Логично, что такую красоту используют для анимаций. transform легко анимируется с помощью свойства transition или ключевых кадров ( @keyframes ).

Анимация с помощью transition

Свойство transition позволяет анимировать плавное изменение свойств CSS от одного состояния к другому за определённое время. Вот пример анимации сдвига элемента при наведении курсора.

В этом примере, когда вы наводите курсор на , он очень по-дизайнерски изгибается. Смотрите:

Анимация с помощью @keyframes

Свойство @keyframes позволяет вам создавать более сложные анимации из нескольких частей. Вот пример анимации, где элемент сначала увеличивается в размере, затем вращается и сдвигается:

@keyframes example < 0% < transform: scale(1); >50% < transform: scale(1.2); >70% < transform: rotate(30deg); >100% < transform: skew(20deg, 10deg);>> div

Выходит, с помощью transform вы можете вращать, масштабировать, перемещать и наклонять элементы, а также применять более сложные преобразования с помощью матриц. Свойство transition помогает анимировать эти эффекты. Главное — не переборщить.

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

Например, если вы захотите расставить элементы на странице с помощью translate , то лучше не надо. Для этого лучше использовать другие CSS свойства, такие как flexbox или grid .

  • CSS свойство transform позволяет применять 2D и 3D преобразования к элементам.
  • С помощью transform можно вращать, масштабировать, перемещать и наклонять элементы.
  • Не все CSS свойства могут быть преобразованы с помощью transform .
  • Вместе с transition получаются неплохие анимации. Главное — знать меру.

Материалы по теме

  • Плавные трансформации на чистом CSS — свойство transition
  • Состояния элементов, чтобы анимировать не только при наведении курсора
  • Как анимация портит ваши сайты — помните, что иногда анимаций бывает слишком много

«Доктайп» — журнал о фронтенде. Читайте, слушайте и учитесь с нами.

Источник

CSS rotate animation examples

CSS rotate animation examples. Use the rotate() CSS function to create rotation animations with CSS. This ranges from loading icons to hamburger menus.

Dec 18, 2021 | Read time 6 minutes

🔔 Table of contents

In this guide, I will go through a few examples to create CSS rotate animations using the rotate() function.

To rotate a HTML element with CSS animations, we use the rotate() CSS function.

For example, in the codepen below — we are rotating the DIV box 45 degrees infinitely

See the Pen Untitled by ⭐ Kentaro ⭐ (@kentaro_au) on CodePen.

Explanation of the above code

For the HTML, we have the following basic structure:

The main part is in the CSS. We first define the @keyframes of the animation.

In this case we want the initial position (%) to rotate 45 degrees to the left.

Then at the end of the animation timeline (100%) we want it to end up rotated 45 degrees to the right.

Now that we have our @keyframe animation configured,

just need to use it on the .element. We are definining the animation to be 2 seconds

and also run it infinitely.

Example #1: Loading rotation animations

The most common use of rotation animations is with loading icons. In the below we create a circular element.

Then add a ball that will rotate 360 degrees around the circular track. This can be acheived with the following

See the Pen CSS Rotate Animation - Example #2 by ⭐ Kentaro ⭐ (@kentaro_au) on CodePen.

Example #2: Loading animations with CSS orbit rotation

The below example shows another loading animation that we can do with CSS rotates.

This one mimics a orbit animation. We use the same @keyframe animation as above — eg rotate(360deg).

However for this one — we have 2 elements rotating, giving the impression of a orbit.

Example #3: Hamburger menu with CSS rotate animation

The below example is of a hamburger menu navigation. Hamburger menu navigation is a way to display navigation menu items.

They are used for mobile devices/ smaller screens.

However they have been popping up on desktop websites aswell.

When you click on the menu/ icon, it will transform from three lines to a cross. They are called hamburger because when

stacked, the icon looks like a hamburger — 2 buns at the top and bottom and a patty in the middle. The below uses CSS rotate

animation to create a cross when a user clicks on the menu.

This uses JavaScript and CSS keyframes to define the rotation of each of the lines to be 45 degrees.

So when the user clicks on the hamburger menu, we assign a .open class.

When it is .open, we rotate the middle hamburger lines and hide the other lines so that it appears like a cross.

Explanation of the rotate() function

The input for the rotate() CSS function accepts a degree value and indicates the angle of rotation.

So for example rotate(0deg) keeps the element at its original position. If you rotate(45deg) then that means the element will rotate 45 degrees clockwise — or “to the right”.

When you use a negative value, the element that rotates anti-clockwise or “to the left”.

For example, in the following codepen, the box will rotate 90 degrees left and then 90 degrees right:

Why would you want to rotate animations?

When adding CSS rotation animations to your website, we want to also keep the following best practices

Don’t animate all the things — just because you can animate something — it doesn’t mean that you should. Animation could get in the way of the user or distort them.

Use of easings — make use of easings so that the animation looks realistic and smooth.

Keep animations between 200-500ms. Anything longer would make the user wait and irritate them most likely. Anything shorter, then the user will not notice it.

Final thoughts

Using CSS animations to rotate an element can be a quick and effective way to add nice interactions to your website/ user interface.

We have seen that they can be used as loading animations, hamburger menu open and closing interactions,

showing custom progress — such as progress of your skills in a portfolio website.

The rotate() function only takes a degree value and rotates the elements on the 2D plane.

It does not shift the layout of the page. When we put in a positive degree value, the element will got to the right, clockwise.

When we put in a negative degree value the element will go to the left, counter clockwise.

As with most things, using animations should be kept minimal to keep the site performant and does not disorient the user.

👋 About the Author

G’day! I am Kentaro a software engineer based in Australia. I have been creating design-centered software for the last 10 years both professionally and as a passion.

My aim to share what I have learnt with you! (and to help me remember 😅)

👉 See Also 👈

Источник

transform

Трансформирует элемент, в частности, позволяет его масштабировать, вращать, сдвигать, наклонять, а также комбинировать виды трансформаций.

Синтаксис

Значения

Функции трансформации

matrix

rotate

Поворот элемента на заданный угол относительно точки трансформации, задаваемой свойством transform-origin .

scale

Масштаб элемента по горизонтали и вертикали.

Значение больше 1 увеличивает масштаб элемента, меньше 1 — уменьшает масштаб.

scaleX

Масштабирует элемент по горизонтали.

scaleY

Масштабирует элемент по вертикали.

skewX

Наклоняет элемент на заданный угол по вертикали.

skewY

Наклоняет элемент на заданный угол по горизонтали.

translate

Сдвигает элемент на заданное значение по горизонтали и вертикали.

translateX

Сдвигает элемент по горизонтали на указанное значение. Положительное значение сдвигает вправо, отрицательное влево.

translateY

Сдвигает элемент по вертикали на указанное значение. Положительное значение сдвигает вниз, отрицательное вверх.

HTML5 CSS3 IE Cr Op Sa Fx

       

Ёжик

В данном примере при наведении курсора на изображение оно поворачивается на 15 градусов по часовой стрелке.

Объектная модель

[window.]document.getElementById(» elementID «).style.transform

Браузеры

Internet Explorer 9 поддерживает нестандартное свойство -ms-transform .

Chrome, Safari, Android и iOS поддерживают нестандартное свойство -webkit-transform .

Opera до версии 12.10 поддерживает нестандартное свойство -o-transform .

Firefox до версии 16.0 поддерживает нестандартное свойство -moz-transform .

Источник

Оцените статью