rotate()

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.
Читайте также:  Python map zip reduced

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.

Табл. 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 раз.
# Повторять один или больше раз через запятую. #

Значения

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

Песочница

Пример

rotate()

В данном примере при наведении указателя на картинку она делает полный оборот по часовой стрелке. Как только укажатель убирается, картинка вращается обратно в исходное положение.

Спецификация

Каждая спецификация проходит несколько стадий одобрения.

  • 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
  • aspect-ratio
  • 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

Источник

Flip / mirror an image horizontally + vertically with css

Im trying to flip an image to display it 4 ways : original (no changes), flipped horizontally, flipped vertically, flipped horizontally + verticly. To do this Im doing the below, it works fine apart from the flip horizontally + vertically, any idea why this wouldnt be working ? Ive made a JS fiddle of the issue here : https://jsfiddle.net/7vg2tn83/

.img-hor < -moz-transform: scaleX(-1); -o-transform: scaleX(-1); -webkit-transform: scaleX(-1); transform: scaleX(-1); filter: FlipH; -ms-filter: "FlipH"; >.img-vert < -moz-transform: scaleY(-1); -o-transform: scaleY(-1); -webkit-transform: scaleY(-1); transform: scaleY(-1); filter: FlipV; -ms-filter: "FlipV"; >.img-hor-vert

4 Answers 4

It wasn’t working before because you were overriding the transform in your css. So instead of doing both, it just did the last one. Sort of like if you did background-color twice, it would override the first one.

To perform a reflection you can use, the transform CSS property along with the rotate() CSS function in this format:

transform: rotateX() rotateY(); 

The function rotateX() will rotate an element along the x-axis and the function rotateY() will rotate an element along the y-axis. I find my approach intuitive in that one can visualize the rotation mentally. In your example, the solution using my approach would be:

.img-hor < transform: rotateY(180deg); // Rotate 180 degrees along the y-axis >.img-vert < transform: rotateX(180deg); // Rotate 180 degrees along the x-axis >.img-hor-vert < transform: rotateX(180deg) rotateY(180deg); // Rotate 180 degrees on both >

Источник

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