- How to rotate an image in HTML
- The 2D rotations
- The Syntax
- The 3D rotation
- The syntax and descriptions
- Few Extra Information for the 3D rotation
- A Coding Sample
- rotate()
- Синтаксис
- Значения
- Песочница
- Пример
- Спецификация
- Браузеры
- Рецепты
- Справочник CSS
- rotate()
- Синтаксис
- Значения
- Примеры
- Базовый пример
- HTML
- CSS
- Result
- Объединение вращения с другим преобразованием
- HTML
- CSS
- Result
- Спецификации
- Поддержка браузерами
- Смотрите также
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
How to rotate an image in HTML
The CSS transform property can rotate an image by a specified angle.
A positive angle creates a clockwise rotation. A negative value creates an anti-clockwise rotation.
There exist two types of rotations, the 2D and 3D rotations. In this tutorial, you’ll learn about both types with a simple hands-on example.
The 2D rotations
The CSS property, transform creates the 2D rotations with help of a CSS function, rotate() .
The browser rotates an object to a specified angle in a two-dimensional plane. A two-dimensional plane has two dimensions, horizontal (X) and vertical (Y) dimensions.
The Syntax
The general syntax of the CSS property, transform to rotate an image using a CSS function, rotate( ) .
The CSS rotate() function helps to specify a transformation that rotates an image. This function accepts the rotation angle as a mandatory parameter.
The 3D rotation
A 3D rotation considers the depth dimension (Z) too along with other dimensions. Thus, you need to specify the axis of the rotation too along with the angle.
You can use functions, rotateX() , rotateY(), and rotateZ() for 3D rotations.
The syntax and descriptions
The syntax of functions rotateX() , rotateY(), and rotateZ() are as follows —
transform: rotateX(angle); // Rotates along with X axis to a specified angle transform: rotateY(angle); // Rotates along with Y axis to a specified angle transform: rotateZ(angle); // Rotates along with Z axis to a specified angle
Few Extra Information for the 3D rotation
The CSS function, rotate3d() allows you to specify both the axis and angle for a 3D rotation in a single function. Here comes the general syntax of the function
tranform: rotate3d(X,Y,Z,angle);
The parameters for this function are as follows
- X, Y, Z — Holds the coordinates of vector for rotation. These parameters can have a value within the range of 0 to 1.
- angle — Specifies the rotation angle.
A Coding Sample
Here comes a simple and easy-to-follow coding sample that rotates images. You can write or copy the below HTML source code in your HTML file, index.html
html lang="en"> head> title>A Sample Web Pagetitle> link rel="stylesheet" href="style.css"> head> body> img src="/photo-1.jpg" alt="Image 1" class="img1"> img src="/photo-1.jpg" alt="Image 1" class="img2"> img src="/photo-1.jpg" alt="Image 1" class="img3"> img src="/photo-1.jpg" alt="Image 1" class="img4"> img src="/photo-1.jpg" alt="Image 1" class="img5"> img src="/photo-1.jpg" alt="Image 1" class="img6"> body> html>
Your CSS file, style.css should have below source code
.img1 < transform: rotate(90deg); > .img2 < transform: rotate(-90deg); > .img3 < transform: rotateX(45deg); > .img4 < transform: rotateY(-45deg); > .img5 < transform: rotateZ(90deg); > .img6 < transform: rotate3d(1, 1, 0, 60deg); >
The above example uses a single image to perform both the 2D and 3D examples. It used all rotate() functions we have learned so far in this tutorial.
You can try with more values to gain more clarity on how they work to rotate an image.
Get my free e-book to prepare for the technical interview or start to Learn Full-Stack JavaScript
rotate()
Функция rotate(α) поворачивает элемент в двумерном пространстве вокруг точки вращения на заданный угол α. Точка вращения по умолчанию располагается в центре элемента и может быть изменена с помощью свойства transform-origin.
Повороты на разные углы с помощью rotate(α) продемонстрированы в табл. 1.
transform: rotate(0) | Исходное изображение. | |
transform: rotate(90deg) | Поворот на 90° по часовой стрелке. | |
transform: rotate(-90deg) | Поворот на 90° против часовой стрелки. | |
transform: rotate(180deg) | Поворот на 180°. |
Синтаксис
Синтаксис
Описание | Пример | |
---|---|---|
Указывает тип значения. | ||
A && B | Значения должны выводиться в указанном порядке. | && |
A | B | Указывает, что надо выбрать только одно значение из предложенных (A или B). | normal | small-caps |
A || B | Каждое значение может использоваться самостоятельно или совместно с другими в произвольном порядке. | width || count |
[ ] | Группирует значения. | [ crop || cross ] |
* | Повторять ноль или больше раз. | [,]* |
+ | Повторять один или больше раз. | + |
? | Указанный тип, слово или группа не является обязательным. | inset? |
Повторять не менее A, но не более B раз. | ||
# | Повторять один или больше раз через запятую. | # |
Значения
Положительное значение поворачивает элемент на заданный угол по часовой стрелке, отрицательное значение поворачивает элемент против часовой стрелки.
Песочница
Пример
!DOCTYPE>
В данном примере при наведении указателя на картинку она делает полный оборот по часовой стрелке. Как только укажатель убирается, картинка вращается обратно в исходное положение.
Спецификация
Каждая спецификация проходит несколько стадий одобрения.
- Recommendation ( Рекомендация ) — спецификация одобрена W3C и рекомендована как стандарт.
- Candidate Recommendation ( Возможная рекомендация ) — группа, отвечающая за стандарт, удовлетворена, как он соответствует своим целям, но требуется помощь сообщества разработчиков по реализации стандарта.
- Proposed Recommendation ( Предлагаемая рекомендация ) — на этом этапе документ представлен на рассмотрение Консультативного совета W3C для окончательного утверждения.
- Working Draft ( Рабочий проект ) — более зрелая версия черновика после обсуждения и внесения поправок для рассмотрения сообществом.
- Editor’s draft ( Редакторский черновик ) — черновая версия стандарта после внесения правок редакторами проекта.
- Draft ( Черновик спецификации ) — первая черновая версия стандарта.
Браузеры
В таблице браузеров применяются следующие обозначения.
- — элемент полностью поддерживается браузером;
- — элемент браузером не воспринимается и игнорируется;
- — при работе возможно появление различных ошибок, либо элемент поддерживается с оговорками.
Число указывает версию браузреа, начиная с которой элемент поддерживается.
Рецепты
Справочник CSS
- !important
- ::after
- ::backdrop
- ::before
- ::first-letter
- ::first-line
- ::placeholder
- ::selection
- :active
- :blank
- :checked
- :default
- :disabled
- :empty
- :enabled
- :first-child
- :first-of-type
- :focus
- :focus-within
- :fullscreen
- :hover
- :in-range
- :indeterminate
- :invalid
- :lang
- :last-child
- :last-of-type
- :link
- :not
- :nth-child
- :nth-last-child
- :nth-last-of-type
- :nth-of-type
- :only-child
- :only-of-type
- :optional
- :out-of-range
- :placeholder-shown
- :read-only
- :read-write
- :required
- :root
- :target
- :valid
- :visited
- @charset
- @document
- @font-face
- @import
- @keyframes
- @media
- @page
- @supports
- @viewport
- 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
- backdrop-filter
- backface-visibility
- background
- background-attachment
- background-blend-mode
- background-clip
- background-color
- background-image
- background-origin
- background-position
- background-position-x
- background-position-y
- background-repeat
- background-size
- block-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-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
- caption-side
- caret-color
- clear
- clip
- 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-family
- font-kerning
- font-size
- font-stretch
- font-style
- font-variant
- font-weight
- height
- hyphens
- image-rendering
- justify-content
- left
- letter-spacing
- line-clamp
- line-height
- list-style
- list-style-image
- list-style-position
- list-style-type
- margin
- margin-bottom
- margin-left
- margin-right
- margin-top
- marks
- max-height
- max-width
- min-height
- min-width
- mix-blend-mode
- object-fit
- opacity
- order
- orphans
- outline
- outline-color
- outline-offset
- outline-style
- outline-width
- overflow
- overflow-x
- overflow-y
- padding
- padding-block
- padding-block-end
- padding-block-start
- padding-bottom
- padding-inline
- padding-inline-end
- padding-inline-start
- padding-left
- padding-right
- padding-top
- page-break-after
- page-break-before
- page-break-inside
- perspective
- perspective-origin
- place-content
- pointer-events
- position
- quotes
- resize
- right
- scroll-behavior
- tab-size
- table-layout
- text-align
- text-align-last
- text-decoration
- text-decoration-color
- text-decoration-line
- text-decoration-skip-ink
- text-decoration-style
- text-emphasis
- text-emphasis-color
- text-emphasis-position
- text-emphasis-style
- text-fill-color
- text-indent
- text-orientation
- text-overflow
- text-shadow
- text-stroke
- text-stroke-color
- text-stroke-width
- 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
- widows
- width
- word-break
- word-spacing
- word-wrap
- writing-mode
- z-index
- zoom
rotate()
Функция CSS rotate () определяет преобразование, которое перемещает элемент вокруг неподвижной точки (как определено свойством transform-origin (en-US), не деформируя его. Количество движения определяется заданным углом; если положительно, движение будет по часовой стрелке, если оно отрицательное, оно будет против часовой стрелки. Вращение на 180 ° называется точечным отражением.
Синтаксис
Значения
Декартовы координаты на ℝ 2 | Однородные координаты на ℝℙ 2 | Декартовы координаты на ℝ 3 | Однородные координаты на ℝℙ 3 |
---|---|---|---|
cos(a) -sin(a) sin(a) cos(a) | cos(a) -sin(a) 0 sin(a) cos(a) 0 0 0 1 | cos(a) -sin(a) 0 sin(a) cos(a) 0 0 0 1 | cos(a) -sin(a) 0 0 sin(a) cos(a) 0 0 0 0 1 0 0 0 0 1 |
[cos(a) sin(a) -sin(a) cos(a) 0 0] |
Примеры
Базовый пример
HTML
div>Normaldiv> div class="rotated">Rotateddiv>
CSS
div width: 80px; height: 80px; background-color: skyblue; > .rotated transform: rotate(45deg); /* Equal to rotateZ(45deg) */ background-color: pink; >
Result
Объединение вращения с другим преобразованием
Если вы хотите применить к элементу несколько преобразований, будьте осторожны с порядком, в котором вы указываете свои преобразования. Например, если вы вращаете перед сдвигом, сдвиг произойдёт относительно новой оси вращения!
HTML
div>Normaldiv> div class="rotate">Rotateddiv> div class="rotate-translate">Rotated + Translateddiv> div class="translate-rotate">Translated + Rotateddiv>
CSS
div position: absolute; left: 40px; top: 40px; width: 100px; height: 100px; background-color: lightgray; > .rotate background-color: transparent; outline: 2px dashed; transform: rotate(45deg); > .rotate-translate background-color: pink; transform: rotate(45deg) translateX(180px); > .translate-rotate background-color: gold; transform: translateX(180px) rotate(45deg); >
Result
Спецификации
Поддержка браузерами
BCD tables only load in the browser
Смотрите также
Found a content problem with this page?
This page was last modified on 5 дек. 2022 г. by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.