Transform
Содержание:
- Введение в CSS трансформации
- Translation (Moving)
- CSS Properties
- The matrix() Method
- CSS Transform Properties
- CSS 2D Transform Methods
- How to Use CSS Transitions?
- More Transition Examples
- CSS Transition Properties
- Значения свойства
- CSS Reference
- CSS Properties
- CSS 2D Transform Methods
- transform:rotate(x) — вращение объекта
- Центр трансформации
- Когда применяются свойства offset?
- Property Values
- CSS Tutorial
- Specify the Speed Curve of the Transition
- Scaling (Resizing)
Введение в CSS трансформации
CSS трансформации используют для изменения вида, поворота и других преобразований элемента. Все эти настройки выставляются в обычных таблицах стилей, и когда вы открываете страницу, то уже видите готовый результат трансформации. Для того чтобы увидеть само преобразование из одного вида в другой (анимацию трансформации), к элементу можно прикрутить какое-то событие (например, событие mouseover);
В примере, указанном ниже, мы расположили 4 абсолютно одинаковых div-а с рамкой в 2px. Для трансформации данных элементов в браузерах, работающих на webkit, добавляем префикс -webkit-transform:
| div 1 | Перемещён вправо -webkit-transform: translate(3em,0); |
| div 2 | Повёрнут на 30 градусов по часовой стрелке -webkit-transform: rotate(30deg); |
| div 3 | Смещён влево и вниз -webkit-transform: translate(-3em,1em); |
| div 4 | Увеличен вдвое -webkit-transform: scale(2); |

Без данных трансформаций div-ы будут выглядеть абсолютно одинаково.
Translation (Moving)
Translates an element on the 2D plane.
The CSS function repositions an element in the horizontal and/or vertical directions.
This transformation is characterized by a two-dimensional vector. Its coordinates define how much the element moves in each direction.
The function is specified as either one or two values.
— More Info : https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/translate
Translates an element horizontally.
The CSS function repositions an element horizontally on the 2D plane.
Syntax : . ( is a length value representing the abscissa of the translating vector.)
— More Info : https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/translateX
Translates an element vertically.
The CSS function repositions an element vertically on the 2D plane.
Syntax : . ( is a length value representing the ordinate of the translating vector.)
— More Info : https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/translateY
CSS Properties
align-contentalign-itemsalign-selfallanimationanimation-delayanimation-directionanimation-durationanimation-fill-modeanimation-iteration-countanimation-nameanimation-play-stateanimation-timing-functionbackface-visibilitybackgroundbackground-attachmentbackground-blend-modebackground-clipbackground-colorbackground-imagebackground-originbackground-positionbackground-repeatbackground-sizeborderborder-bottomborder-bottom-colorborder-bottom-left-radiusborder-bottom-right-radiusborder-bottom-styleborder-bottom-widthborder-collapseborder-colorborder-imageborder-image-outsetborder-image-repeatborder-image-sliceborder-image-sourceborder-image-widthborder-leftborder-left-colorborder-left-styleborder-left-widthborder-radiusborder-rightborder-right-colorborder-right-styleborder-right-widthborder-spacingborder-styleborder-topborder-top-colorborder-top-left-radiusborder-top-right-radiusborder-top-styleborder-top-widthborder-widthbottombox-decoration-breakbox-shadowbox-sizingbreak-afterbreak-beforebreak-insidecaption-sidecaret-color@charsetclearclipclip-pathcolorcolumn-countcolumn-fillcolumn-gapcolumn-rulecolumn-rule-colorcolumn-rule-stylecolumn-rule-widthcolumn-spancolumn-widthcolumnscontentcounter-incrementcounter-resetcursordirectiondisplayempty-cellsfilterflexflex-basisflex-directionflex-flowflex-growflex-shrinkflex-wrapfloatfont@font-facefont-familyfont-feature-settingsfont-kerningfont-sizefont-size-adjustfont-stretchfont-stylefont-variantfont-variant-capsfont-weightgapgridgrid-areagrid-auto-columnsgrid-auto-flowgrid-auto-rowsgrid-columngrid-column-endgrid-column-gapgrid-column-startgrid-gapgrid-rowgrid-row-endgrid-row-gapgrid-row-startgrid-templategrid-template-areasgrid-template-columnsgrid-template-rowshanging-punctuationheighthyphens@importisolationjustify-content@keyframesleftletter-spacingline-heightlist-stylelist-style-imagelist-style-positionlist-style-typemarginmargin-bottommargin-leftmargin-rightmargin-topmax-heightmax-width@mediamin-heightmin-widthmix-blend-modeobject-fitobject-positionopacityorderoutlineoutline-coloroutline-offsetoutline-styleoutline-widthoverflowoverflow-xoverflow-ypaddingpadding-bottompadding-leftpadding-rightpadding-toppage-break-afterpage-break-beforepage-break-insideperspectiveperspective-originpointer-eventspositionquotesresizerightrow-gapscroll-behaviortab-sizetable-layouttext-aligntext-align-lasttext-decorationtext-decoration-colortext-decoration-linetext-decoration-styletext-indenttext-justifytext-overflowtext-shadowtext-transformtoptransformtransform-origintransform-styletransitiontransition-delaytransition-durationtransition-propertytransition-timing-functionunicode-bidiuser-selectvertical-alignvisibilitywhite-spacewidthword-breakword-spacingword-wrapwriting-modez-index
The matrix() Method
The method combines all the 2D transform methods into one.
The matrix() method take six parameters, containing mathematic functions,
which allows you to rotate, scale, move (translate), and skew elements.
The parameters are as follow: matrix(scaleX(),skewY(),skewX(),scaleY(),translateX(),translateY())
Example
div
{
transform: matrix(1, -0.3, 0, 1, 0, 0);}
CSS Transform Properties
The following table lists all the 2D transform properties:
| Property | Description |
|---|---|
| transform | Applies a 2D or 3D transformation to an element |
| transform-origin | Allows you to change the position on transformed elements |
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 ❯
How to Use CSS Transitions?
To create a transition effect, you must specify two things:
- the CSS property you want to add an effect to
- the duration of the effect
Note: If the duration part is not specified, the transition will have no effect, because the default value is 0.
The following example shows a 100px * 100px red <div> element. The <div>
element has also specified a transition effect for the width property, with a duration of 2 seconds:
Example
div
{ width: 100px; height: 100px;
background: red; transition: width 2s;
}
The transition effect will start when the specified CSS property (width) changes value.
Now, let us specify a new value for the width property when a user mouses over the <div> element:
Example
div:hover
{
width: 300px;
}
Notice that when the cursor mouses out of the element, it will gradually change back to its original style.
More Transition Examples
The CSS transition properties can be specified one by one, like this:
Example
div
{ transition-property: width;
transition-duration: 2s;
transition-timing-function: linear;
transition-delay: 1s;
}
or by using the shorthand property :
Example
div
{
transition: width 2s linear 1s;
}
CSS Transition Properties
The following table lists all the CSS transition properties:
| Property | Description |
|---|---|
| transition | A shorthand property for setting the four transition properties into a single property |
| transition-delay | Specifies a delay (in seconds) for the transition effect |
| transition-duration | Specifies how many seconds or milliseconds a transition effect takes to complete |
| transition-property | Specifies the name of the CSS property the transition effect is for |
| transition-timing-function | Specifies the speed curve of the transition effect |
❮ Previous
Next ❯
Значения свойства
| Значение | Описание |
|---|---|
| none | Преобразование не применяется. |
| matrix(n,n,n,n,n,n) | Применяет 2D преобразование с помощью матрицы из шести значений. |
| matrix3d(n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n) | Применяет 3D преобразование с помощью матрицы из шестнадцати(4х4) значений. |
| translate(x,y) | Функция translate позволяет перемещать элементы влево, вправо, вверх или вниз. Эта функция аналогична поведению position: relative; При использовании этой функции, можно сдвигать элементы не влияя на поток документа. |
| translate3d(x,y,z) | Применяет 3D смещение. |
| translateX(x) | Определяет смещение, только по оси Х. |
| translateY(y) | Определяет смещение, только по оси У. |
| translateZ(z) | Определяет 3D смещение, только по оси Z. |
| scale(x,y) | Функция scale(x,y) масштабирует элемент горизонтально и вертикально. Если указано только одно значение, оно будет использовано сразу и для горизонтального масштабирования и для вертикального. Например, scale(1) оставит элемент такого же размера, scale(2) удвоит его пропорции, scale(0.5) уменьшит элемент в 2 раза и так далее. Предоставление различных значений будет искажать элемент. Масштабируемый элемент будет увеличиваться от своего центра или уменьшаться к нему, другими словами центр элемента будет всегда находится в одной и той же точке, не зависимо от его размера. Таково поведение элемента по умолчанию, чтобы изменить это можно воспользоваться свойством transform-origin. |
| scale3d(x,y,z) | Применяет 3D преобразование масштаба. |
| scaleX(x) | Определяет преобразование масштаба по оси Х. |
| scaleY(y) | Определяет преобразование масштаба по оси У. |
| scaleZ(z) | Определяет 3D преобразование масштаба по оси Z. |
| rotate(angle) | Функция rotate() поворачивает элемент вокруг точки происхождения по заданному значению угла. Как и в случае с функцией scale(), по умолчанию точка происхождения — это центр элемента. |
| rotate3d(x,y,z,angle) | Определяет 3D поворот. |
| rotateX(angle) | Определяет 3D поворот вдоль оси Х. |
| rotateY(angle) | Определяет 3D поворот вдоль оси У. |
| rotateZ(angle) | Определяет 3D поворот вдоль оси Z. |
| skew(x, y) | Функция skew(x, y) определяет наклон по осям X и Y. Как и следовало ожидать, x определяет наклон оси X,а y определяет наклон оси Y. Если второй параметр опущен, то перекос элемента произойдёт только по оси X. |
| skewX(angle) | Определяет 2D преобразование наклона вдоль оси Х. |
| skewY(angle) | Определяет 2D преобразование наклона вдоль оси У. |
| perspective(n) | Определяет перспективу для преобразования 3D элемента. |
| inherit | Указывает, что значение наследуется от родительского элемента. |
Пример
CSS Свойство:
transform:
Результат:
Демонстрация работы свойтсва transform.
CSS Код:
#myDIV { background-color: lightblue; transform: rotate(10deg); }
Кликните на любое значение свойства, чтобы увидеть результат
CSS Reference
CSS ReferenceCSS Browser SupportCSS SelectorsCSS FunctionsCSS Reference AuralCSS Web Safe FontsCSS Font FallbacksCSS AnimatableCSS UnitsCSS PX-EM ConverterCSS ColorsCSS Color ValuesCSS Default ValuesCSS Entities
CSS Properties
align-content
align-items
align-self
all
animation
animation-delay
animation-direction
animation-duration
animation-fill-mode
animation-iteration-count
animation-name
animation-play-state
animation-timing-function
backface-visibility
background
background-attachment
background-blend-mode
background-clip
background-color
background-image
background-origin
background-position
background-repeat
background-size
border
border-bottom
border-bottom-color
border-bottom-left-radius
border-bottom-right-radius
border-bottom-style
border-bottom-width
border-collapse
border-color
border-image
border-image-outset
border-image-repeat
border-image-slice
border-image-source
border-image-width
border-left
border-left-color
border-left-style
border-left-width
border-radius
border-right
border-right-color
border-right-style
border-right-width
border-spacing
border-style
border-top
border-top-color
border-top-left-radius
border-top-right-radius
border-top-style
border-top-width
border-width
bottom
box-decoration-break
box-shadow
box-sizing
break-after
break-before
break-inside
caption-side
caret-color
@charset
clear
clip
clip-path
color
column-count
column-fill
column-gap
column-rule
column-rule-color
column-rule-style
column-rule-width
column-span
column-width
columns
content
counter-increment
counter-reset
cursor
direction
display
empty-cells
filter
flex
flex-basis
flex-direction
flex-flow
flex-grow
flex-shrink
flex-wrap
float
font
@font-face
font-family
font-feature-settings
font-kerning
font-size
font-size-adjust
font-stretch
font-style
font-variant
font-variant-caps
font-weight
gap
grid
grid-area
grid-auto-columns
grid-auto-flow
grid-auto-rows
grid-column
grid-column-end
grid-column-gap
grid-column-start
grid-gap
grid-row
grid-row-end
grid-row-gap
grid-row-start
grid-template
grid-template-areas
grid-template-columns
grid-template-rows
hanging-punctuation
height
hyphens
@import
isolation
justify-content
@keyframes
left
letter-spacing
line-height
list-style
list-style-image
list-style-position
list-style-type
margin
margin-bottom
margin-left
margin-right
margin-top
max-height
max-width
@media
min-height
min-width
mix-blend-mode
object-fit
object-position
opacity
order
outline
outline-color
outline-offset
outline-style
outline-width
overflow
overflow-x
overflow-y
padding
padding-bottom
padding-left
padding-right
padding-top
page-break-after
page-break-before
page-break-inside
perspective
perspective-origin
pointer-events
position
quotes
resize
right
row-gap
scroll-behavior
tab-size
table-layout
text-align
text-align-last
text-decoration
text-decoration-color
text-decoration-line
text-decoration-style
text-indent
text-justify
text-overflow
text-shadow
text-transform
top
transform
transform-origin
transform-style
transition
transition-delay
transition-duration
transition-property
transition-timing-function
unicode-bidi
user-select
vertical-align
visibility
white-space
width
word-break
word-spacing
word-wrap
writing-mode
z-index
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 ❯
transform:rotate(x) — вращение объекта
Чтобы вращать элемент существует команда rotate(x). Она позволяет повернуть объект на x градусов по часовой или против часовой стрелке. Значение х нужно указывать в градусах deg
Пример #1. Вращение объекта в html через трансформацию
На странице преобразуется в следующее
Примечание
Свойства:
Нужны для корректной работы в старых версиях браузеров. В следующих примерах мы также будем их писать.
Пример #2. Вращение объекта в html при наведении курсора
Создадим класс kvadrat2 и пропишем для него псевдокласс :hover, в котором и будет прописано вращение и смена цвета на более светлый (с #444 на #888).
На странице преобразуется в следующее
Но это вращение происходит резко и не смотрится «эффектно». Это можно легко исправить сделав сглаживание. В следующем примере будет реализована анимация.
Пример #3. Плавное вращение при наведении курсора (анимация) в html
Для плавного вращения (или другими словами сглаживания) необходимо прописать еще одно свойство transition. Это свойство отвечает за время и эффект сглаживания. В данном примере рассматривается самый простой случай с переходом за 1 секунду с линейной скоростью linear
На странице преобразуется в следующее
Стало гораздо симпатичнее и такая анимация дает множество возможностей для создания эффектов на сайте только за счет CSS.
Центр трансформации
По умолчанию все трансформации элемента происходят относительно точки, расположенной в его центре. Собственно, также это происходит и в Photoshop, и в Illustrator. Но если в графических программах эту точку можно переместить визуально, то в css-свойствах за ее положение отвечает :
transform-origin: center;
transform-origin: 50% 50%;
transform-origin: 20px 100px;
transform-origin: 3em 1.2rem;
transform-origin: 35px 2em;
|
1 2 3 4 5 |
transform-origincenter; transform-origin50%50%; transform-origin20px100px; transform-origin3em1.2rem; transform-origin35px2em; |
Значение этого свойства по умолчанию: , или . Задание в свойстве например, помещает начало координат в 20 пикселей от левого края объекта и в 100 пикселей от его верха. Трансформации каждой точки в локальной системе координат объекта рассчитываются относительно этого центра.
Вы можете задавать координаты центр трансформации с помощью ключевых слов:
- по горизонтали:
- по вертикали:
Посмотрите на разницу в отображении трансформации относительно точки трансформации, которая расположена в различных координатах:
See the Pen CSS property transform-origin by Elen (@ambassador) on CodePen.dark
Еще раз посмотреть все варианты трансформаций вы можете в примере ниже:
See the Pen Css3 Transform by Elen (@ambassador) on CodePen.18892
Когда применяются свойства offset?
Три новых независимых свойства преобразования применяются до свойств . Функции применяются после .
- (distance, anchor, rotate …)
- (здесь можете устанавливать свой порядок)
Так, например, использование базовой анимации вернёт различный визуальный результат, если объединить ее с или .
See this code transform:translate vs translate with offset-path on x.xhtml.ru.
Довольно интересно (и часто сбивает с толку) то, как все они взаимодействуют друг с другом. Однако знание последовательности преобразований — это уже половина решения в прояснении магии, происходящей с , отдельными свойствами преобразования и траекторией движения.
Property Values
| Value | Description | Play it |
|---|---|---|
| none | Defines that there should be no transformation | Play it » |
| matrix(n,n,n,n,n,n) | Defines a 2D transformation, using a matrix of six values | Play it » |
| matrix3d (n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n) |
Defines a 3D transformation, using a 4×4 matrix of 16 values | |
| translate(x,y) | Defines a 2D translation | Play it » |
| translate3d(x,y,z) | Defines a 3D translation | |
| translateX(x) | Defines a translation, using only the value for the X-axis | Play it » |
| translateY(y) | Defines a translation, using only the value for the Y-axis | Play it » |
| translateZ(z) | Defines a 3D translation, using only the value for the Z-axis | |
| scale(x,y) | Defines a 2D scale transformation | Play it » |
| scale3d(x,y,z) | Defines a 3D scale transformation | |
| scaleX(x) | Defines a scale transformation by giving a value for the X-axis | Play it » |
| scaleY(y) | Defines a scale transformation by giving a value for the Y-axis | Play it » |
| scaleZ(z) | Defines a 3D scale transformation by giving a value for the Z-axis | |
| rotate(angle) | Defines a 2D rotation, the angle is specified in the parameter | Play it » |
| rotate3d(x,y,z,angle) | Defines a 3D rotation | |
| rotateX(angle) | Defines a 3D rotation along the X-axis | Play it » |
| rotateY(angle) | Defines a 3D rotation along the Y-axis | Play it » |
| rotateZ(angle) | Defines a 3D rotation along the Z-axis | Play it » |
| skew(x-angle,y-angle) | Defines a 2D skew transformation along the X- and the Y-axis | Play it » |
| skewX(angle) | Defines a 2D skew transformation along the X-axis | Play it » |
| skewY(angle) | Defines a 2D skew transformation along the Y-axis | Play it » |
| perspective(n) | Defines a perspective view for a 3D transformed element | |
| initial | Sets this property to its default value. Read about initial | |
| inherit | Inherits this property from its parent element. Read about inherit |
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
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 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;}
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



