Трансформация

Практический пример использования трансформаций и hover-эффектов

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

hover block

.box img {
display: block;
max-width: 100%;
transition: transform .7s;
}
.box:hover img{
transform: scale(1.3) rotate(-7deg);
}
.box:hover {
box-shadow: 0 3px 20px rgba(0,0,0,.6);
transform: translateY(10px);
}

1
2
3
4
5
6
7
8
9
10
11
12

.box img{

displayblock;

max-width100%;

transitiontransform.7s;

}

.boxhoverimg{

transformscale(1.3)rotate(-7deg);

}

.boxhover{

box-shadow3px20pxrgba(,,,.6);

transformtranslateY(10px);

}

Все стили вы можете посмотреть на вкладке , а разметку — на вкладке . Для того чтобы поворот картинки не был заметен, она помещена в div-обертку, для которого назначено свойство . Поэтому все, что выходит за пределы этого div-а, обрезается.

See the Pen CSS transition and transform by Elen (@ambassador) on CodePen.18892

Пример создания различных фигур на основе свойства transform и border

Вы можете «нарисовать» с помощью css различные фигуры — от ромба до сердца. Для этого вам понадобится не только свойство , но и для псевдоэлементов ::before и/или ::after.

See the Pen shapes with css-transform property by Elen (@ambassador) on CodePen.18892

Пример с картами

В этом примере вы найдете варианты использования свойства transform не только для самих карт, но и для их мастей, причем стили написаны и для элементов, и для псевдоэлементов.

See the Pen CSS Aces by Suzanne Aitchison (@aitchiss) on CodePen.18892

Rotation (2D)

Rotates an element around a fixed point on the 2D plane.

The CSS function defines a transformation that rotates an element around a fixed point on the 2D plane, without deforming it. The amount of rotation created by is specified by an angle value expressed in degrees, gradians, radians, or turns. If positive, the movement will be clockwise; if negative, it will be counter-clockwise. (A rotation by 180° is called point reflection.)

The axis of rotation passes through an origin, defined by the CSS property.

— More info: developer.mozilla.org/en-US/docs/Web/CSS/transform-function/rotate

Transition

Отвечает за плавность анимации блока. Имеет несколько свойств, которые можно задать одним. Взаимодействует не только с transform (например, с помощью transition можно сделать плавное изменение цвета или размера блока). Не поддерживается устаревшими браузерами (решается с помощью специфических -moz-transition, -webkit-transition и т.д.).

transition-property – задает свойство элемента, которое будет анимироваться
transition-duration – Задает время анимации в секундах. 1 равен одной секунде.
transition-timing-function – Тип анимации, где могут быть указаны:
– ease – медленная анимация с замедлением в середине
– linear – медленная анимация с ускорением к концу
– ease-in – анимация плавно начинается
– ease-out – анимация плавно заканчивается
– ease-in-out – анимация плавно начинается и плавно заканчивается
transition-delay – задержка перед началом анимации
cubic-bezier – анимация по Кривой Безье
transition(property, duration, timing-function) – задает все вышеперечисленные свойства, исключая cubic-beizer

Стоит отметить, что CSS3-аналог transition — animate, который работает с ключевыми кадрами (@keyframes)

Взаимодействие и примеры

transition в сочетании с transform дают нам плавную и гибкую анимацию без javascript.

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

HTML:

Код

<div class=»container»>
<h4>translate(15px, 15px)</h4>
<div class=»transformed t-rotate» data-content=»Translate»></div>
</div>

CSS:

Код

.container {
position: relative;
display: inline-block;
height: 180px;
margin: 0 1em 1em;
}
.transformed:before {
content: attr(data-content);
display: block;
margin: 0;
padding: 7px 0;
text-align: center;
font-weight: normal;
background: rgba(255,255,255,.7);
}
.transformed {
position: absolute;
bottom: 0;
background: yellowgreen;
opacity: 0.7;
}
.t-rotate {
transform: rotate(-20deg);
transition(transform, 1s, ease-in-out);
}
</b>

Спасибо за прочтение.
P.S. что-то совсем уж длинно получилось, извиняюсь.

Комментарии

Используйте MatrixTransform класс для создания пользовательских преобразований, не предоставляемых RotateTransform ScaleTransform SkewTransform классами,, и TranslateTransform .Use the MatrixTransform class to create custom transformations that are not provided by the RotateTransform, ScaleTransform, SkewTransform, and TranslateTransform classes.

В двумерной плоскости x-y для преобразований используется матрица 3X3.A 2-D x-y plane uses a 3×3 matrix for transformations. Матрицы аффинных преобразований можно умножать для формирования линейных преобразований, например вращения и наклона (сдвига), за которыми следует перевод.You can multiply affine transformation matrices to form linear transformations, such as rotation and skew (shear) that are followed by translation.

Последний столбец матрицы аффинного преобразования равен (0, 0, 1); Поэтому необходимо указать только элементы в первых двух столбцах.An affine transformation matrix has its final column equal to (0, 0, 1); therefore, you only have to specify the members in the first two columns.

Windows Presentation Foundation (WPF) Matrix имеет следующую структуру:A Windows Presentation Foundation (WPF) Matrix has the following structure:

M11 M12
M21 M22
OffsetX OffsetY 11

Элементы в последней строке, OffsetX и OffsetY , представляют значения перевода.The members in the last row, OffsetX and OffsetY, represent translation values.

Методы и свойства обычно задают матрицу преобразования как вектор, содержащий только шесть элементов. они выглядят следующим образом:Methods and properties usually specify the transformation matrix as a vector that has only six members; they are as follows:

(M11, M12, M21, M22, OffsetX, OffsetY)(M11, M12, M21, M22, OffsetX, OffsetY)

Specify the Speed Curve of the Transition

The property specifies the speed curve of the transition effect.

The transition-timing-function property can have the following values:

  • — specifies a transition effect with a slow start, then fast, then end slowly (this is default)
  • — specifies a transition effect with the same speed from start to end
  • — specifies a transition effect with a slow start
  • — specifies a transition effect with a slow end
  • — specifies a transition effect with a slow start and end
  • — lets you define your own values in a cubic-bezier function

The following example shows the some of the different speed curves that can be used:

Example

#div1 {transition-timing-function: linear;}#div2
{transition-timing-function: ease;}#div3 {transition-timing-function:
ease-in;}#div4 {transition-timing-function: ease-out;}#div5
{transition-timing-function: ease-in-out;}

Преобразование элемента FrameworkElementTransforming a FrameworkElement

Чтобы применить преобразования к FrameworkElement , создайте Transform и примените его к одному из двух свойств, FrameworkElement предоставляемых классом.To apply transformations to a FrameworkElement, create a Transform and apply it to one of the two properties that the FrameworkElement class provides:

  • LayoutTransform — Преобразование, которое применяется перед проходом макета.LayoutTransform – A transform that is applied before the layout pass. После применения преобразования система разметки обрабатывает преобразованные размер и положение элемента.After the transform is applied, the layout system processes the transformed size and position of the element.

  • RenderTransform — Преобразование, изменяющее внешний вид элемента, но применяемое после завершения прохода макета.RenderTransform – A transform that modifies the appearance of the element but is applied after the layout pass is complete. Используя RenderTransform свойство вместо LayoutTransform свойства, можно получить преимущества производительности.By using the RenderTransform property instead of the LayoutTransform property, you can obtain performance benefits.

Какое свойство следует использовать?Which property should you use? Из-за преимуществ производительности, предоставляемых ею, используйте RenderTransform свойство везде, где это возможно, особенно при использовании анимированных Transform объектов.Because of the performance benefits that it provides, use the RenderTransform property whenever possible, especially when you use animated Transform objects. Используйте LayoutTransform свойство при масштабировании, повороте или наклоне, и необходимо, чтобы родительский элемент элемента подпревратился в преобразованный размер элемента.Use the LayoutTransform property when scaling, rotating, or skewing and you need the parent of the element to adjust to the transformed size of the element

Обратите внимание, что при использовании со LayoutTransform свойством TranslateTransform объекты не оказывают влияния на элементы.Note that, when they are used with the LayoutTransform property, TranslateTransform objects appear to have no effect on elements. Это вызвано тем, что система разметки возвращает преобразуемый элемент в исходное положение в ходе обработки.That is because the layout system returns the translated element to its original position as part of its processing

Дополнительные сведения о разметке в Windows Presentation Foundation (WPF)Windows Presentation Foundation (WPF) см. в разделе Общие сведения о разметке.For additional information about layout in Windows Presentation Foundation (WPF)Windows Presentation Foundation (WPF), see Layout overview.

CSS 2D Transform Methods

Function Description
matrix(n,n,n,n,n,n) Defines a 2D transformation, using a matrix of six values
translate(x,y) Defines a 2D translation, moving the element along the X- and the Y-axis
translateX(n) Defines a 2D translation, moving the element along the X-axis
translateY(n) Defines a 2D translation, moving the element along the Y-axis
scale(x,y) Defines a 2D scale transformation, changing the elements width and height
scaleX(n) Defines a 2D scale transformation, changing the element’s width
scaleY(n) Defines a 2D scale transformation, changing the element’s height
rotate(angle) Defines a 2D rotation, the angle is specified in the parameter
skew(x-angle,y-angle) Defines a 2D skew transformation along the X- and the Y-axis
skewX(angle) Defines a 2D skew transformation along the X-axis
skewY(angle) Defines a 2D skew transformation along the Y-axis

❮ Previous
Next ❯

Пример: поворот элемента FrameworkElement на 45 градусовExample: Rotate a FrameworkElement 45 Degrees

В следующем примере используется RotateTransform для поворота кнопки по часовой стрелке на 45 градусов.The following example uses a RotateTransform to rotate a button clockwise by 45 degrees. Кнопка содержится в элементе с StackPanel двумя другими кнопками.The button is contained in a StackPanel that has two other buttons.

По умолчанию объект RotateTransform вращается вокруг точки (0, 0).By default, a RotateTransform rotates about the point (0, 0). Так как в примере не задана центральная точка, то кнопка поворачивается вокруг точки (0, 0), т. е. левого верхнего угла.Because the example does not specify a center value, the button rotates about the point (0, 0), which is its upper-left corner. RotateTransformАтрибут применяется к RenderTransform свойству.The RotateTransform is applied to the RenderTransform property. На рисунке ниже показан результат преобразования.The following illustration shows the result of the transformation.

Поворот на 45 градусов по часовой стрелке вокруг левого верхнего углаClockwise rotation 45 degrees from upper-left corner

В следующем примере также используется RotateTransform для поворота кнопки 45 градусов по часовой стрелке, но она также задает RenderTransformOrigin для кнопки значение (0,5, 0,5).The next example also uses a RotateTransform to rotate a button 45 degrees clockwise, but it also sets the RenderTransformOrigin of the button to (0.5, 0.5). Значение RenderTransformOrigin свойства определяется относительно размера кнопки.The value of the RenderTransformOrigin property is relative to the size of the button. В результате кнопка поворачивается вокруг центра, а не вокруг левого верхнего угла.As a result, the rotation is applied to the center of the button, instead of its upper-left corner. На рисунке ниже показан результат преобразования.The following illustration shows the result of the transformation.

Поворот на 45 градусов по часовой стрелке вокруг центраClockwise rotation 45 degrees around center

В следующем примере LayoutTransform для поворота кнопки используется свойство вместо RenderTransform Свойства.The following example uses the LayoutTransform property instead of the RenderTransform property to rotate the button. При этом преобразование влияет на разметку кнопки, что приводит к запуску полного прохода системы разметки.This causes the transformation to affect the layout of the button, which triggers a full pass by the layout system. Так как размер кнопки был изменен, то после поворота кнопки также изменяется ее положение.As a result, the button is rotated and then repositioned because its size has changed. На рисунке ниже показан результат преобразования.The following illustration shows the result of the transformation.

Поворот кнопки с использованием LayoutTransformLayoutTransform used to rotate the button

Scaling (Resizing)

Scales an element up or down on the 2D plane.

The CSS function defines a transformation that resizes an element on the 2D plane. Because the amount of scaling is defined by a vector, it can resize the horizontal and vertical dimensions at different scales.

This scaling transformation is characterized by a two-dimensional vector. Its coordinates define how much scaling is done in each direction. If both coordinates are equal, the scaling is uniform (isotropic) and the aspect ratio of the element is preserved (this is a homothetic transformation).

When a coordinate value is outside the range, the element grows along that dimension; when inside, it shrinks. If it is negative, the result a point reflection in that dimension. A value of 1 has no effect.

The function is specified with either one or two values, which represent the amount of scaling to be applied in each direction.

— More Info : https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/scale

Scales an element up or down horizontally.

The CSS function defines a transformation that resizes an element along the x-axis (horizontally).

It modifies the abscissa of each element point by a constant factor, except when the scale factor is 1, in which case the function is the identity transform. The scaling is not isotropic, and the angles of the element are not conserved. scaleX(-1) defines an axial symmetry, with a vertical axis passing through the origin (as specified by the property).

— More Info : https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/scaleX

Scales an element up or down vertically.

The CSS function defines a transformation that resizes an element along the y-axis (vertically).

It modifies the ordinate of each element point by a constant factor, except when the scale factor is 1, in which case the function is the identity transform. The scaling is not isotropic, and the angles of the element are not conserved. scaleY(-1) defines an axial symmetry, with a horizontal axis passing through the origin (as specified by the transform-origin property).

— More Info : https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/scaleY

Когда применяются свойства offset?

Три новых независимых свойства преобразования применяются до свойств . Функции применяются после .

  1. (distance, anchor, rotate …)
  2. (здесь можете устанавливать свой порядок)

Так, например, использование базовой анимации вернёт различный визуальный результат, если объединить ее с или .

See this code transform:translate vs translate with offset-path on x.xhtml.ru.

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

3D-функции

Мы видели, как функции трансформации работают на плоскости, вдоль осей х и у.

Например:

  • У translate() до двух параметров:
    • translate(x)
    • translate(x, y)
  • translateX() только для оси х
  • translateY() только для оси у

Но для всех этих функций также есть 3D-версии.

Например, для translate() есть версия translate3d(), которая выполняет преобразование в трёх измерениях, а это значит, что она также включает в себя ось z (кроме того существует отдельная функция translateZ).

Параметр z в основном заставляет элемент двигаться ближе и дальше, в зависимости от уменьшения или увеличения значения. Это как увеличение и уменьшение масштаба.

Зелёный блок поднимается на 200px «вверх» по оси z, как будто становясь ближе к нам.

К родительскому элементу требуется применить perspective: 500px, чтобы трёхмерное пространство стало заметным. В качестве альтернативы также может быть использовано transform: perspective(500px).

CSS Tutorial

CSS HOMECSS IntroductionCSS SyntaxCSS SelectorsCSS How ToCSS CommentsCSS Colors
Colors
RGB
HEX
HSL

CSS Backgrounds
Background Color
Background Image
Background Repeat
Background Attachment
Background Shorthand

CSS Borders
Borders
Border Width
Border Color
Border Sides
Border Shorthand
Rounded Borders

CSS Margins
Margins
Margin Collapse

CSS PaddingCSS Height/WidthCSS Box ModelCSS Outline
Outline
Outline Width
Outline Color
Outline Shorthand
Outline Offset

CSS Text
Text Color
Text Alignment
Text Decoration
Text Transformation
Text Spacing
Text Shadow

CSS Fonts
Font Family
Font Web Safe
Font Fallbacks
Font Style
Font Size
Font Google
Font Pairings
Font Shorthand

CSS IconsCSS LinksCSS ListsCSS Tables
Table Borders
Table Size
Table Alignment
Table Style
Table Responsive

CSS DisplayCSS Max-widthCSS PositionCSS OverflowCSS Float
Float
Clear
Float Examples

CSS Inline-blockCSS AlignCSS CombinatorsCSS Pseudo-classCSS Pseudo-elementCSS OpacityCSS Navigation Bar
Navbar
Vertical Navbar
Horizontal Navbar

CSS DropdownsCSS Image GalleryCSS Image SpritesCSS Attr SelectorsCSS FormsCSS CountersCSS Website LayoutCSS UnitsCSS SpecificityCSS !important

2D-трансформации элементов

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

1. Функции 2D-трансформации transform

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

Допустимые значения:

matrix() — любое числоtranslate(), translateX(), translateY() — единицы длины (положительные и отрицательные), %scale(), scaleX(), scaleY() — любое числоrotate() — угол (deg, grad, rad или turn)skew(), skewX(), skewY() — угол (deg, grad, rad)

Функция Описание
none Значение по умолчанию, означает отсутствие трансформации. Также отменяет трансформацию для элемента из группы трансформируемых элементов.
matrix(a, c, b, d, x, y) Смещает элементы и задает способ их трансформации, позволяя объединить несколько функций 2D-трансформаций в одной. В качестве трансформации допустимы поворот, масштабирование, наклон и изменение положения.
Значение a изменяет масштаб по горизонтали. Значение от 0 до 1 уменьшает элемент, больше 1 — увеличивает.
Значение c деформирует (сдвигает) стороны элемента по оси Y, положительное значение — вверх, отрицательное — вниз.
Значение b деформирует (сдвигает) стороны элемента по оси X, положительное значение — влево, отрицательное — вправо.
Значение d изменяет масштаб по вертикали. Значение меньше 1 уменьшает элемент, больше 1 — увеличивает.
Значение x смещает элемент по оси X, положительное — вправо, отрицательное — влево.
Значение y смещает элемент по оси Y, положительное значение — вниз, отрицательное — вверх.
translate(x,y) Сдвигает элемент на новое место, перемещая относительно обычного положения вправо и вниз, используя координаты X и Y, не затрагивая при этом соседние элементы. Если нужно сдвинуть элемент влево или вверх, то нужно использовать отрицательные значения.
translateX(n) Сдвигает элемент относительно его обычного положения по оси X.
translateY(n) Сдвигает элемент относительно его обычного положения по оси Y.
scale(x,y) Масштабирует элементы, делая их больше или меньше. Значения от 0 до 1 уменьшают элемент. Первое значение масштабирует элемент по ширине, второе — по высоте. Отрицательные значения отображают элемент зеркально.
scaleX(n) Функция масштабирует элемент по ширине, делая его шире или уже. Если значение больше единицы, элемент становится шире, если значение находится между единицей и нулем, элемент становится уже. Отрицательные значения отображают элемент зеркально по горизонтали.
scaleY(n) Функция масштабирует элемент по высоте, делая его выше или ниже. Если значение больше единицы, элемент становится выше, если значение находится между единицей и нулем — ниже. Отрицательные значения отображают элемент зеркально по вертикали.
rotate(угол) Поворачивает элементы на заданное количество градусов, отрицательные значения от -1deg до -360deg поворачивают элемент против часовой стрелки, положительные — по часовой стрелке. Значение rotate(720deg) поворачивает элемент на два полных оборота.
skew(x-угол,y-угол) Используется для деформирования (искажения) сторон элемента относительно координатных осей. Если указано одно значение, второе будет определено браузером автоматически.
skewX(угол) Деформирует стороны элемента относительно оси X.
skewY(угол) Деформирует стороны элемента относительно оси Y.
initial Устанавливает значение свойства в значение по умолчанию.
inherit Наследует значение свойства от родительского элемента.

Синтаксис

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

See the Pen EaNbLX by HeleN (@nazarelen) on CodePen.

2. Точка трансформации transform-origin

Свойство позволяет сместить центр трансформации, относительно которого происходит изменение положения/размера/формы элемента. Значение по умолчанию — center, или 50% 50%. Задаётся только для трансформированных элементов. Не наследуется.

transform-origin
Значения:
ось Х(left, center, right, длина, %)
ось Y(top, center, bottom, длина, %)
Пара значений, заданная с помощью ключевых слов, единиц длины или процентов определяет, относительно какой части элемента будет происходить трансформация. Значения больше 100% увеличивают область трансформации элемента.
initial Устанавливает значение свойства в значение по умолчанию.
inherit Наследует значение свойства от родительского элемента.

Синтаксис

See the Pen aNQNva by Elena Nazarova (@nazarelen) on CodePen.

3. Множественные трансформации

Можно объединить несколько трансформаций одного элемента, перечислив их через пробел в порядке проявления.

div {transform: scale(1.5) rotate(-10deg);}

CSS3-переходы
CSS3-анимация

Skewing (Distortion)

Skews an element on the 2D plane.

The skew() CSS function defines a transformation that skews an element on the 2D plane.

This transformation is a shear mapping (transvection) that distorts each point within an element by a certain angle in the horizontal and vertical directions. The coordinates of each point are modified by a value proportionate to the specified angle and the distance to the origin; thus, the farther from the origin a point is, the greater will be the value added it.

The skew() function is specified with either one or two values, which represent the amount of skewing to be applied in each direction.

— More Info : https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/skew

: Skews an element in the horizontal direction.

The skewX() CSS function defines a transformation that skews an element in the horizontal direction on the 2D plane.

This transformation is a shear mapping (transvection) that distorts each point within an element by a certain angle in the horizontal direction. The abscissa coordinate of each point is modified by a value proportionate to the specified angle and the distance to the origin; thus, the farther from the origin a point is, the greater will be the value added it.

— More Info : https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/skewX

Skews an element in the vertical direction.

The skewY() CSS function defines a transformation that skews an element in the vertical direction on the 2D plane.

This transformation is a shear mapping (transvection) that distorts each point within an element by a certain angle in the vertical direction. The ordinate coordinate of each point is modified by a value proportionate to the specified angle and the distance to the origin; thus, the farther from the origin a point is, the greater will be the value added it.

— More Info : https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/skewY

Смещение translate()

Очень удобное свойство, которое позволяет смещать элементы, которые не позиционированы абсолютно или относительно. В качестве аргументов можно указывать число в %, px, em, rem и т.п., причем как положительные, так и отрицательные. В случае использования % величина смещения берется от ширины или высоты элемента.

При использовании функции translate() с одним параметром смещение будет происходить по горизонтали (вправо — при положительных значениях, влево — при отрицательных значениях). Можно указать 2 параметра — тогда смещение будет и по горизонтали, и по вертикали одновременно. Для того чтобы сместить элемент по одной из осей, можно использовать функции  translateX() или  translateY() для горизонтального и вертикального смещения:

transform: translate()

.box1 {
transform: translate(-45px);
}
.box2 {
transform: translate(20%, 20%);
}
.box3 {
transform: translateX(2em);
}
.box4 {
transform: translateY(3rem);
}
.box5 {
transition: transform .7s;
}
.box5:hover {
transform: translate(3rem, 2em);
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

.box1{

transformtranslate(-45px);

}

.box2{

transformtranslate(20%,20%);

}

.box3{

transformtranslateX(2em);

}

.box4{

transformtranslateY(3rem);

}

.box5{

transitiontransform.7s;

}

.box5hover{

transformtranslate(3rem,2em);

}

See the Pen CSS-property transform: translate() by Elen (@ambassador) on CodePen.dark

Трехмерное масштабирование элементов

Следующая функция, которую мы рассмотрим это функция scale3d(), она определяет трехмерное преобразование путем масштабирования элемента по оси X, по оси Y и по оси Z. Перейдем к примеру:

<!DOCTYPE html>
<html>
<head>
	<meta charset = "UTF-8">
	<title>Трехмерное масштабирование элементов по осям</title>
<style>
.static {
display: inline-block; /* блочно-строчные элементы (выстраиваем элементы в линейку) */
margin: 10px; /* внешние отступы со всех сторон */
background: gray; /* цвет заднего фона */
}
div {
width: 180px; /* ширина элемента */
height: 100px; /* высота элемента */
line-height: 100px; /* высота строки (выраывниваем по вертикали) */
text-align: center; /* горизонтальное выравнивание текста по центру */
transition: 0.2s; /* переходный эффект составляет 200 миллисекунд (0,2 секунды) */
}
.test2, .test4, .test6 {background: orange;} /* цвет заднего фона */
.test, .test3, .test5 {background: plum;} /* цвет заднего фона */
.test:hover {
transform: perspective(500px) rotateX(45deg) scale3d(1,2,1); /* используем несколько функций преобразования для элемента при наведении (перспектива, поворот по оси X, трехмерное масштабирование) */
}
.test2:hover {
transform: perspective(500px) rotateX(45deg) scale3d(2,1,1); /* используем несколько функций преобразования для элемента при наведении (перспектива, поворот по оси X, трехмерное масштабирование) */
}
.test3:hover {
transform: perspective(500px) rotateX(45deg) scale3d(1,1,2); /* используем несколько функций преобразования для элемента при наведении (перспектива, поворот по оси X, трехмерное масштабирование) */
}
.test4:hover {
transform: perspective(500px) rotateX(45deg) scale3d(-1,-2,-1); /* используем несколько функций преобразования для элемента при наведении (перспектива, поворот по оси X, трехмерное масштабирование) */
}
.test5:hover {
transform: perspective(500px) rotateX(45deg) scale3d(0.5,1,1); /* используем несколько функций преобразования для элемента при наведении (перспектива, поворот по оси X, трехмерное масштабирование) */
}
.test6:hover {
transform: perspective(500px) rotateX(45deg) scale3d(0.5,0.5,2); /* используем несколько функций преобразования для элемента при наведении (перспектива, поворот по оси X, трехмерное масштабирование) */
}
</style>
</head>
	<body>
		<div class = "static"><div class = "test">scale3d(1,2,1)</div></div>
		<div class = "static"><div class = "test2">scale3d(2,1,1)</div></div>
		<div class = "static"><div class = "test3">scale3d(1,1,2)</div></div><br>
		<div class = "static"><div class = "test4">scale3d(-1,-2,-1)</div></div>
		<div class = "static"><div class = "test5">scale3d(0.5,1,1)</div></div>
		<div class = "static"><div class = "test6">scale3d(0.5,0.5,2)</div></div>
	</body>
</html>

В этом примере были использованы различные значения функции scale3d(), благодаря которой, мы масштабируем элемент сразу по трём осям.
Для демонстрации работы трехмерного масштабирования функцией scale3d(), мы добавили функцию rotateX(), которая поворачивает наш элемент по оси X и функцию преобразования perspective(), которая определяет перспективу обзора элемента, создавая для пользователя иллюзию глубины.

Результат нашего примера:

Рис. 180 Трехмерное масштабирование элементов по осям (функция преобразования элемента scale3d).

Transform: translate

The CSS property is for moving elements to the left or right side, or up and down. It accepts two values:

  • One value means that element will be moved up and down or side-to-side. Remember that negative values move elements to the left, positive ones to the right.
  • The second value pushes the element down. Negative values move elements up, while positive ones move them down.

The following example moves an HTML element to the right and down with the two values:

Example Copy

It is also possible to move elements along the horizontal or vertical axis. The moves elements vertically, while pushes them horizontally.

Example Copy

You also can move elements in the 3D space by using CSS or the . These functions create an effect that elements move closer or further away from the user.

Example Copy

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *