CSS transform-origin Property
Example
Establish the foundational positioning of a rotated element.
div
{
Transform
: rotate(45deg);
transform-origin
: 20% 40%;
}
Try it Yourself »
Definition and Usage
By utilizing the
property, you have the ability to adjust the placement of
transformed elements
.
2D transformations have the capability to alter the x and y-axis of an element, while 3D transformations possess the ability to modify the z-axis of an element.
To gain a deeper comprehension of the
property, watch a demonstration.
Please be aware that the utilization of this property is only effective when used in conjunction with the transform property.
For a better understanding of this property in relation to 3D transforms, it is recommended to view a demo.
Show demo ❯
Default value: | 50% 50% 0 | |
---|---|---|
Inherited: | no | |
Animatable: | Indeed, explore information regarding the concept of ‘animatable’ and give it a try. | |
Version: | CSS3 | |
JavaScript syntax: | The transform origin of the object is set to «0 0» using the style property. Give it a try. |
Browser Support
The property’s full support in browsers is indicated by the corresponding numbers in the table.
The first version that worked with a prefix is specified by numbers followed by -webkit-, -moz-, or -o-.
Property | ||||||
---|---|---|---|---|---|---|
Two-value syntax of transform-origin. | The values are 36.0 and 4.0 with the prefix -webkit-. |
10.0 9.0 -ms- |
The given text, «16.0 3.5 -moz-«, should be paraphrased to avoid repetition while retaining its meaning. |
The text to be paraphrased: «»» 9.0 3.2 -webkit- «»» Paraphrased version: «»» Version 9.0 is followed by version 3.2, which includes the prefix -webkit-. |
23.0 15.0 with the -webkit- prefix 10.5 with the -o- prefix |
|
Three-value syntax of transform-origin | The values are 36.0 and 12.0 for the -webkit- prefix. | 10.0 |
The text to be paraphrased is as follows: «16.0 10.0 -moz-» Rephrased version: «16.0, with a value of 10.0 using the -moz- prefix. |
9.0 4.0 with the prefix -webkit- «»». |
The values are 23.0 and 15.0 for the -webkit- prefix. |
Property Values
Property Value | Description | |
---|---|---|
x-axis |
The x-axis placement of the view is determined by the following possible values: <li> , <li> , <li> , <li> , and <li> . |
|
y-axis |
Specifies the position of the view along the y-axis. Available options include: <li> — <li> — <li> — <li> — <li> |
|
z-axis |
The «z-axis» determines the placement of the view in 3D transformations. Various values are available for this purpose. | |
initial | Assigns the default value to this property. Learn more about the initial value. | |
inherit | This property is inherited from the parent element. Learn more about the concept of inheritance. |
CSS tutorial: CSS
2d transforms
CSS tutorial:
CSS 3D Transforms
Property of transformOrigin in HTML DOM reference
Transform scale in css Code Example, Get code examples like
Tags:
css transforms module level 1
a demonstration of various transform values
Examples
See Using CSS transforms for examples.
Live Examples
Code | Sample |
---|---|
<div class="box1"> </div> .box1 { margin: 0.5em; width: 3em; height: 3em; border: solid 1px; background-color: palegreen; transform: none; -webkit-transform: none; -moz-transform: none; -o-transform: none; } |
|
<div class="box2"> </div> .box2 { margin: 0.5em; width: 3em; height: 3em; border: solid 1px; background-color: palegreen; transform: rotate(30deg); -webkit-transform: rotate(30deg); -moz-transform: rotate(30deg); -o-transform: rotate(30deg); } |
|
<div class="box3"> </div> .box3 { margin: 0.5em; width: 3em; height: 3em; border: solid 1px; background-color: palegreen; transform-origin: 0 0; transform: rotate(30deg); -webkit-transform: rotate(30deg); -moz-transform: rotate(30deg); -o-transform: rotate(30deg); } |
|
<div class="box4"> </div> .box4 { margin: 0.5em; width: 3em; height: 3em; border: solid 1px; background-color: palegreen; transform-origin: 100% 100%; transform: rotate(30deg); -webkit-transform: rotate(30deg); -moz-transform: rotate(30deg); -o-transform: rotate(30deg); } |
|
<div class="box5"> </div> .box5 { margin: 0.5em; width: 3em; height: 3em; border: solid 1px; background-color: palegreen; transform-origin: -10em -30em; transform: rotate(30deg); -webkit-transform: rotate(30deg); -moz-transform: rotate(30deg); -o-transform: rotate(30deg); } |
|
<div class="box6"> </div> .box6 { margin: 0.5em; width: 3em; height: 3em; border: solid 1px; background-color: palegreen; transform: scale(1.9); -webkit-transform: scale(1.9); -moz-transform: scale(1.9); -o-transform: scale(1.9); } |
|
<div class="box7"> </div> .box7 { margin: 0.5em; width: 3em; height: 3em; border: solid 1px; background-color: palegreen; transform: scale(1.9); -webkit-transform: scale(1.9); -moz-transform: scale(1.9); -o-transform: scale(1.9); transform-origin: 0 0; -webkit-transform-origin: 0 0; -moz-transform-origin: 0 0; -o-transform-origin: 0 0; } |
|
<div class="box8"> </div> .box8 { margin: 0.5em; width: 3em; height: 3em; border: solid 1px; background-color: palegreen; transform: scale(1.9); -webkit-transform: scale(1.9); -moz-transform: scale(1.9); -o-transform: scale(1.9); transform-origin: 100% -30%; -webkit-transform-origin: 100% -30%; -moz-transform-origin: 100% -30%; -o-transform-origin: 100% -30%; } |
|
<div class="box9"> </div> .box9 { margin: 0.5em; width: 3em; height: 3em; border: solid 1px; background-color: palegreen; transform: skewX(50deg); trasnform-origin: 100% -30%; -webkit-transform: skewX(50deg); -moz-transform: skewX(50deg); -o-transform: skewX(50deg); } |
|
<div class="box10"> </div> .box10 { margin: 0.5em; width: 3em; height: 3em; border: solid 1px; background-color: palegreen; transform: skewY(50deg); -webkit-transform: skewY(50deg); -moz-transform: skewY(50deg); -o-transform: skewY(50deg); transform-origin: 100% -30%; -webkit-transform-origin: 100% -30%; -moz-transform-origin: 100% -30%; -o-transform-origin: 100% -30%; } |
Syntax
/* One-value syntax */ transform-origin: 2px; transform-origin: bottom; /* x-offset y-offset */ transform-origin: 3cm 2px; /* y-offset x-offset-keyword */ transform-origin: 2px left; /* x-offset-keyword y-offset */ transform-origin: left 2px; /* x-offset-keyword y-offset-keyword */ transform-origin: right top; /* y-offset-keyword x-offset-keyword */ transform-origin: top right; /* x-offset y-offset z-offset */ transform-origin: 2px 30% 10px; /* y-offset x-offset-keyword z-offset */ transform-origin: 2px left 10px; /* x-offset-keyword y-offset z-offset */ transform-origin: left 5px -3px; /* x-offset-keyword y-offset-keyword z-offset */ transform-origin: right bottom 2cm; /* y-offset-keyword x-offset-keyword z-offset */ transform-origin: bottom right 2cm; /* Global values */ transform-origin: inherit; transform-origin: initial; transform-origin: unset;
Values
- x-offset
- Is a or a describing how far from the left edge of the box the origin of the transform is set.
- offset-keyword
- Is one of the , , , or keyword describing the corresponding offset.
- y-offset
- Is a or a describing how far from the top edge of the box the origin of the transform is set.
- x-offset-keyword
- Is one of the , or keyword describing how far from the left edge of the box the origin of the transform is set.
- y-offset-keyword
- Is one of the , or keyword describing how far from the top edge of the box the origin of the transform is set.
- z-offset
- Is a (and never a which would make the statement invalid) describing how far from the user eye the z=0 origin is set.
The keywords are convenience shorthands and match the following values:
keyword | value |
---|---|
Formal syntax
<percentage> <length> left center right top bottom <percentage> <length> left center right <percentage> <length> top center bottom <length>
CSS transform-origin Example
HTML with CSS Code
<!DOCTYPE html> <html> <head> <style> .backBox{width: 120px; height: 120px; background-color: gainsboro; margin: auto;} .frontBox{width: 120px; height: 120px; background-color: chocolate;} .a{transform: rotate(15deg);} .b{transform: rotate(15deg); transform-origin: 100px 0px;} .c{transform: rotate(15deg); transform-origin: -100px 0px;} .d{transform: rotate(15deg); transform-origin: 0px 100px;} .e{transform: rotate(15deg); transform-origin: 0px -100px;} .f{transform: rotate(15deg); transform-origin: 0 0;} .g{transform: rotate(15deg); transform-origin: 100% 100%;} .h{transform: rotate(15deg); transform-origin: 100% 100% 100%;} .i{transform: scale(1.4, 0.7); transform-origin: 0 0;} .j{transform: scale(1.4, 0.7); transform-origin: 0% bottom;} .k{transform: scale(1.4, 0.7); transform-origin: 100% bottom;} .l{transform: scale(1.4, 0.7); transform-origin: 0% top;} .m{transform: skewX(45deg); transform-origin: 70% 20%;} .n{transform: skewX(45deg); transform-origin: 70% 20% 90%;} .o{transform: skewY(45deg); transform-origin: 70% 20%;} .p{transform: skewY(45deg); transform-origin: 70%;} </style> </head> <body> <h2>transform: rotate(15deg)</h2> <div class="backBox"> <div class="frontBox a"></div> </div> <h2>transform: rotate(15deg); transform-origin: 100px 0px</h2> <div class="backBox"> <div class="frontBox b"></div> </div> <h2>transform: rotate(15deg); transform-origin: -100px 0px</h2> <div class="backBox"> <div class="frontBox c"></div> </div> <h2>transform: rotate(15deg); transform-origin: 0px 100px</h2> <div class="backBox"> <div class="frontBox d"></div> </div> <h2>transform: rotate(15deg); transform-origin: 0px -100px</h2> <div class="backBox"> <div class="frontBox e"></div> </div> <h2>transform: rotate(15deg); transform-origin: 0 0</h2> <div class="backBox"> <div class="frontBox f"></div> </div> <h2>transform: rotate(15deg); transform-origin: 100% 100%</h2> <div class="backBox"> <div class="frontBox g"></div> </div> <h2>transform: rotate(15deg); transform-origin: 100% 100% 100%</h2> <div class="backBox"> <div class="frontBox h"></div> </div> <h2>transform: scale(1.4, 0.7); transform-origin: 0 0</h2> <div class="backBox"> <div class="frontBox i"></div> </div> <h2>transform: scale(1.4, 0.7); transform-origin: 0% bottom</h2> <div class="backBox"> <div class="frontBox j"></div> </div> <h2>transform: scale(1.4, 0.7); transform-origin: 100% bottom</h2> <div class="backBox"> <div class="frontBox k"></div> </div> <h2>transform: scale(1.4, 0.7); transform-origin: 0% top</h2> <div class="backBox"> <div class="frontBox l"></div> </div> <h2>transform: skewX(45deg); transform-origin: 70% 20%</h2> <div class="backBox"> <div class="frontBox m"></div> </div> <h2>transform: skewX(45deg); transform-origin: 70% 20% 90%</h2> <div class="backBox"> <div class="frontBox n"></div> </div> <h2>transform: skewY(45deg); transform-origin: 70% 20%</h2> <div class="backBox"> <div class="frontBox o"></div> </div> <h2>transform: skewY(45deg); transform-origin: 70%</h2> <div class="backBox"> <div class="frontBox p"></div> </div> </body> </html>
Output
transform: skewY(45deg); transform-origin: 70%
In above example, the back box, or the box whose background color is gainsboro, is fix. Whereas the
transformation is applied to the front box, whose background color is chocolate. I’ve done this, so that the
change in the origin of transformation can easily be spotted.
Note — The rotate() function rotates an element on the
plane.
Note — The scale() function resizes an element on x-axis and
y-axis both at once.
Note — The skewY() function skews an element vertically.
« Previous TutorialNext Tutorial »
Определение и использование
Свойство позволяет изменять положение преобразованных элементов.
2D преобразования могут изменять оси x и y элемента. 3D преобразования также могут изменять ось z элемента.
Чтобы лучше понять свойство the property,
просмотр демо-версии.
Примечание: Это свойство должно использоваться вместе с свойством transform.
Совет: Чтобы лучше понять свойство, это свойство для 3D трансформация,
просмотр демо-версии.
Значение по умолчанию: | 50% 50% 0 |
---|---|
Унаследованный: | нет |
Анимируемый: | да Прочитайте о animatable Попробовать |
Версия: | CSS3 |
JavaScript синтаксис: |
object.style.transformOrigin=»0 0″ Попробовать |
Description of values:
bottom |
|
The origin is aligned to the bottom of the element. | |||||
center |
|
The origin is aligned to the center of the element. | |||||
horizontal position in length |
|
The horizontal position of the origin in length units relative to the left side of the element. For the supported length units, see the length page. | |||||
horizontal position in percentage |
|
The horizontal position of the origin is the specified percentage of the width of the element relative to the left side of the element. | |||||
left |
|
The origin is aligned to the left side of the element. | |||||
right |
|
The origin is aligned to the right side of the element. | |||||
top |
|
The origin is aligned to the top of the element. | |||||
vertical position in length |
|
The vertical position of the origin in length units relative to the top of the element. For the supported length units, see the length page. | |||||
vertical position in percentage |
|
The vertical position of the origin is the specified percentage of the height of the element relative to the top of the element. |
Default: 50% 50%.
The rectangle defined by the top, left, right and bottom values includes the padding, scrollBars and border, but excludes the margin and outline.
If only one value is given and it applies to horizontal positioning, the vertical position will be set to 50%. Otherwise, if the single value applies to vertical positioning, the horizontal position will be set to 50%.
Функции преобразований
Свойство transform способно совершать ряд операций над элементами с помощью функций преобразований. Рассмотрим каждую по очереди.
Перемещение (translate)
Функция translate позволяет переместить элемент относительно своего начального расположения. Синтаксис данной функции:
Значения X и Y могут быть в любых единицах измерения и показывают величину перемещения элемента вдоль соответствующей оси.
Изменения значения для оси X перемещает элемент влево/вправо, для оси Y — вверх и вниз. Положительные значения перемещают элемент в направлениях вниз и вправо, отрицательные — вверх и влево.
Важно отметить, что позиция самого элемента в потоке не меняется. Неважно, какой из функций преобразования мы воспользовались, зарезервированное изначально место элемента сохранится, будь он даже частью флексбоксов или гридов
В примере ниже у нас есть 3 дочерних элемента, выровненных с помощью флексбокс. Когда мы применяем преобразование к среднему, алгоритм флексбокса его игнорирует и оставляет все дочерние элементы на своих местах.
В целом, поведение очень похоже на то, когда мы пытаемся спозиционировать элемент с помощью свойств top / left / right / bottom. Основное отличие — элемент не вырывается из потока и не влияет на расположение соседних блоков.
Если нам необходимо переместить элемент только по одной оси, мы можем использовать translateX и translateY:
Самое интересное и невероятно мощное в этой функции — выражение перемещения в процентах.
Когда мы используем процентное значение в translate, этот процент относится к собственному размеру элемента, а не к доступному пространству в родительском контейнере.
Таким образом, значение transform: translateY(-100%) переместит элемент вверх ровно на его высоту независимо от ее значения.
Использование перемещения в процентах является одним из ответов на популярный вопрос собеседований «как выровнять элемент по центру?». Вот это решение:
За счет абсолютного позиционирования мы смещаем начало элемента (левый верхний угол) в самый центр родителя, а затем отрицательный translate величиной в половину ширины и высоты элемента делает его полностью отцентрированным. При этом становятся абсолютно не важными ни размеры родителя, ни дочернего элемента.
Стоит также добавить, что значениями для translate могут быть высчитанные с помощью calc() значения и даже переменные.
Масштаб (scale)
Функция scale позволяет увеличить/уменьшить элемент относительно своего начального размера. Синтаксис данной функции:
Значением scale будет коэффициент, на который будет увеличен (если он больше 1) или уменьшен (если меньше 1) элемент. Одно значение scale изменит масштаб всего элемента, а при двух значениях элемент будет масштабироваться по каждой из осей соответствующе.
На первый взгляд может показаться, что масштабируется ширина и высота элемента. Однако тут есть одно большое отличие. Посмотрите, что будет происходить, если в нашем элементе есть текст:
Как видим, текст масштабируется вместе с элементом. Таким образом, с помощью функции scale мы не масштабируем только размер и форму элемента, а влияем на весь элемент и всех его потомков.
Небольшой пример использования scale в верстке информационных карточек при наведении на них:
Поворот (rotate)
Функция rotate поворачивает элемент по/против часовой стрелки на указанное количество градусов.
Как и с функцией scale, поворот элемента затрагивает как сам элемент, так и все его дочерние. Оборот в 360° вернет элемент в то же положение.
Обычно для указания величины поворота используют градусы (deg). Однако, можно использовать еще одну удобную единицу измерения turn, которая показывает, сколько оборотов должен сделать элемент. 1turn = 360°.
Наклон (skew)
Эта функция применяется довольно редко, однако заслуживает не меньшего внимания. Она позволяет исказить элемент путем его наклона вдоль оси.
Размерность указывается в градусах и наклон по-умолчанию осуществляется вдоль оси X.
Чтобы наклонять элемент по оси Y или по обеим осям, запись функции должна быть следующей:
Browser compatibility
- Desktop
- Mobile
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | (Yes) -webkit | 3.5 (1.9.1)-moz16.0 (16.0) | 9.0-ms 10.0 |
10.5-o 12.10 |
3.1-webkit |
Three-value syntax | (Yes) -webkit | (10)-moz16.0 (16.0) | 5.5 (partial) 9.0 -ms 10.0 |
No support | (Yes) -webkit |
Support in SVG | (Yes) | (41) (43) | No support | (Yes) | ? |
Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | ? | ? | ? | 8.1 -webkit | ? | ? |
Three-value syntax | ? | ? | ? | ? | No support | ? |
Support in SVG | ? | (41) (43) | ? | ? | ? | ? |
Internet Explorer 5.5 or later supports a proprietary Matrix Filter which can be used to achieve similar effects.
In addition to the unprefixed support, Gecko 44.0 (Firefox 44.0 / Thunderbird 44.0 / SeaMonkey 2.41) added support for a prefixed version of the property for web compatibility reasons behind the preference , defaulting to . Since Gecko 49.0 (Firefox 49.0 / Thunderbird 49.0 / SeaMonkey 2.46) the preference defaults to .
See MSDN transform-origin documentation.
Percentage handling for values for SVG elements was behind the preference , defaulting to . Keywords and percentages refer to the canvas instead of the object itself. See bug 1209061.
Keywords and percentages refer to the canvas instead of the object itself. See bug 1209061.
Desktop Browsers | Mobile Browsers | |||||||
---|---|---|---|---|---|---|---|---|
Chrome for Desktop | Firefox for Desktop | Internet Explorer for Desktop | Opera for Desktop | Safari for Desktop | Chrome for Android | Internet Explorer Mobile | Opera Mobile | |
Basic Support | YesFull supportPrefixed | 16.0Full support | 10.0Full support | 12.10Full support | 3.1Full supportPrefixed | ? | 11.0Full supportPrefixed | ? |
Three-value syntax | YesFull supportPrefixed | 16.0Full support | 10.0Full support | NoNo support | YesFull supportPrefixed | ? | ? | NoNo support |
Support in SVG | YesFull support | 43.0Full support | NoNo support | YesFull support | ? | 43.0Full support | ? | ? |
Working with Transforms in JavaScript
There are a few things to be aware of when using JavaScript to control transforms.
The CSS names for transform properties are different than the JavaScript names. When using JavaScript to set a property, delete the hyphens from the property name and capitalize the first letter of the following word. The following snippet shows how to set properties for an element with the ID in CSS and JavaScript:
<style> |
#myElement { |
-webkit-transform-origin: 100% 100%; |
-webkit-transform: rotate(45deg); |
} |
</style> |
<script type="text/javascript> |
function tilt() { |
body.getElementById('myElement').style.webkitTransformOrigin = "100% 100%"; |
body.getElementById('myElement').style.webkitTransform = "rotate(45deg)"; |
} |
</scriptt> |
You cannot set a transform property to two consecutive states in a single JavaScript execution cycle. As with all CSS properties, transforms are not applied until the current JavaScript context finishes execution. If you need to set a property to consecutive states, break the code into separate functions and set a timeout; this allows the context to complete. For example, suppose you want to animate a rotation from 0-360 degrees repeatedly. You might do this by disabling the animation, setting the rotation to , enabling the animation, and setting the rotation to . Unless you end the JavaScript context between the two settings, the code will not work. The following snippet shows how to accomplish the task:
function set0() { |
body.getElementById('myElement').style.webkitTransitionProperty = "none"; |
body.getElementById('myElement').style.webkitTransform = "rotate(0deg)"; |
} |
function set360() { |
body.getElementById('myElement').style.webkitTransition = "webkitTransform 1s"; |
body.getElementById('myElement').style.webkitTransform = "rotate(360deg)"; |
} |
function spin() { |
set0(); |
setTimeout(set360, 1); |
} |
If you dynamically trigger transformation of an already-transformed element, the old transforms are lost. You must set the property to a list of all the transforms necessary to bring the element from its native position and orientation to the desired state. gives an example of the necessary steps in the buttons that open and close the lid of the box.
Transforming an element in anhandler may move the element behind other elements so that touch or mouse events are intercepted by those other elements. One solution is to include touch and mouse handlers on any elements that the desired target element may be transformed behind.
If you set theproperty using a list of transform functions as parameters, the functions may be combined into a matrix before being applied. Combining transform functions into a matrix normalizes rotation settings modulo 360 so that a setting of , for example, is normalized to . You can avoid this behavior by using the same set of transform functions every time you transform the element.
You can use theproperty to get an element’s transform. Use the method to obtain the property, as shown in the following snippet:
var theTransform = window.getComputedStyle(element).webkitTransform; |
Try it
The transform origin is the point around which a transformation is applied. For example, the transform origin of the rotate() function is the center of rotation.
In effect, this property wraps a pair of translations around the element’s other transformations. The first translation moves the transform origin to the true origin at ( 0 , 0 ) . Then the other transformations are applied, and because the transform origin is at ( 0 , 0 ) , those transformations act about the transform origin. Finally, the opposite translation is applied, moving the transform origin back to its original location. Consequently, this definition
transform-origin -100% 50%; transform rotate(45deg);
results in the same transformation as
transform-origin 0 0; transform translate(-100%, 50%) rotate(45deg) translate(100%, -50%);
Reading from right to left, translate(100%, -50%) is the translation to bring the transform origin to the true origin, rotate(45deg) is the original transformation, and translate(-100%, 50%) is the translation to restore the transform origin to its original location.
By default, the origin of a transform is center .
Description
The property lets you modify the origin for transformations of an element. For example, the transform-origin of the function is the centre of rotation. (This property is applied by first translating the element by the negated value of the property, then applying the element’s transform, then translating by the property value.)
Not explicitly set values are reset to their corresponding values.
Initial value | |
---|---|
Applies to | transformable elements |
Inherited | no |
Percentages | refer to the size of bounding box |
Media | visual |
Computed value | for the absolute value, otherwise a percentage |
Animatable | yes, as a simple list of , a , or calc(); when both values are lengths, they are interpolated as lengths; when both values are percentages, they are interpolated as percentages; otherwise, both values are converted into a function that is the sum of a length and a percentage (each possibly zero), and these functions have each half interpolated as real numbers. |
Canonical order | One or two values, with length made absolute and keywords translated to percentages |
Possible Values
|
&&
] <length>?
Explanation of the possible values:
x-axis
Possible values for the x-axis are:
- <percentage>
- Defines, as a percentage value, an offset of the transform origin from the top left corner of the element’s bounding box. For example,
- <length>
- Defines, as a fixed length, an offset of the transform origin from the top left corner of the element’s bounding box. For example,
- Places the transformed element at the left of the element’s bounding box.
- Places the transformed element at the center of the element’s bounding box.
- Places the transformed element at the right of the element’s bounding box.
y-axis
Possible values for the y-axis are:
- <percentage>
- Defines, as a percentage value, an offset of the transform origin from the top left corner of the element’s bounding box. For example,
- <length>
- Defines, as a fixed length, an offset of the transform origin from the top left corner of the element’s bounding box. For example,
- Places the transformed element at the top of the element’s bounding box.
- Places the transformed element at the bottom of the element’s bounding box.
z-axis
Possible values for the z-axis are:
- <length>
- Defines, as a fixed length, an offset of the transform origin from the top left corner of the element’s bounding box. For example,
In addition, all CSS properties also accept the following CSS-wide keyword values as the sole component of their property value:
- Represents the value specified as the property’s initial value.
- Represents the computed value of the property on the element’s parent.
- This value acts as either or , depending on whether the property is inherited or not. In other words, it sets all properties to their parent value if they are inheritable or to their initial value if not inheritable.
CSS Animate Transform
All of our examples so far have been static, but we can do better than that. Any CSS transform method can be combined with CSS transitions to produce cool CSS animation effects.
For example, we can code an interactive hover button with the scale() method. Try moving your cursor over the div in the example below:
See the Pen CSS transform: animate 1 by HubSpot (@hubspot) on CodePen.
Or, we can produce a pinwheel-like effect with rotate(). Try hovering over this div:
See the Pen CSS transform: animate 2 by HubSpot (@hubspot) on CodePen.
For a more in-depth look at CSS transitions and how they can apply to the transform property, check out this video tutorial:
Summary
The property lets you modify the origin for transformations of an element. For example, the transform-origin of the function is the centre of rotation. (This property is applied by first translating the element by the negated value of the property, then applying the element’s transform, then translating by the property value.)
Not explicitly set values are reset to their corresponding values.
Initial value | |
---|---|
Applies to | transformable elements |
Inherited | no |
Percentages | refer to the size of bounding box |
Media | visual |
Computed value | for the absolute value, otherwise a percentage |
Animatable | yes, as a simple list of , a , or calc(); when both values are lengths, they are interpolated as lengths; when both values are percentages, they are interpolated as percentages; otherwise, both values are converted into a function that is the sum of a length and a percentage (each possibly zero), and these functions have each half interpolated as real numbers. |
Canonical order | One or two values, with length made absolute and keywords translated to percentages |
Syntax
transform-origin: 2px; transform-origin: bottom; transform-origin: 3cm 2px; transform-origin: 2px left; transform-origin: left 2px; transform-origin: right top; transform-origin: top right; transform-origin: 2px 30% 10px; transform-origin: 2px left 10px; transform-origin: left 5px -3px; transform-origin: right bottom 2cm; transform-origin: bottom right 2cm; transform-origin: inherit; transform-origin: initial; transform-origin: unset;
Values
- x-offset
- Is a or a describing how far from the left edge of the box the origin of the transform is set.
- offset-keyword
- Is one of the , , , or keyword describing the corresponding offset.
- y-offset
- Is a or a describing how far from the top edge of the box the origin of the transform is set.
- x-offset-keyword
- Is one of the , or keyword describing how far from the left edge of the box the origin of the transform is set.
- y-offset-keyword
- Is one of the , or keyword describing how far from the top edge of the box the origin of the transform is set.
- z-offset
- Is a (and never a which would make the statement invalid) describing how far from the user eye the z=0 origin is set.
The keywords are convenience shorthands and match the following values:
keyword | value |
---|---|
Changing the Origin
By default, the origin for transforms is the center of an element’s bounding box. Most HTML and CSS entities use the upper-left corner as the default origin, but for transforms, it is usually more convenient to use the center of an element as a reference point. Consequently, elements rotate around their center by default, and scale up or down from the center out.
To change the origin for transforms of a given element, set the property. The new origin is specified as a distance or percentage from the element’s upper-left corner. For example, the default center origin can be expressed as . Changing the origin to or causes transformation to occur around the upper-left corner of the element.
The code in Listing 7-4 rotates the second box in Figure 7-5 around the top-right corner.
Listing 7-4 Rotating an element around the top-right corner
<div style="width: 300px; |
-webkit-transform: rotate(-45deg); |
-webkit-transform-origin: 100% 0%;"> |
<p>I am rotated about my top-right corner.</p> |
</div> |