scale()

transform

The transform CSS property lets you rotate, scale, skew, or translate an element. It modifies the coordinate space of the CSS visual formatting model.

Try it

If the property has a value different than none , a stacking context will be created. In that case, the element will act as a containing block for any position: fixed; or position: absolute; elements that it contains.

Warning: Only transformable elements can be transform ed. That is, all elements whose layout is governed by the CSS box model except for: non-replaced inline boxes, table-column boxes, and table-column-group boxes.

Syntax

/* Keyword values */ transform: none; /* Function values */ transform: matrix(1, 2, 3, 4, 5, 6); transform: matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); transform: perspective(17px); transform: rotate(0.5turn); transform: rotate3d(1, 2, 3, 10deg); transform: rotateX(10deg); transform: rotateY(10deg); transform: rotateZ(10deg); transform: translate(12px, 50%); transform: translate3d(12px, 50%, 3em); transform: translateX(2em); transform: translateY(3in); transform: translateZ(2px); transform: scale(2, 0.5); transform: scale3d(2.5, 1.2, 0.3); transform: scaleX(2); transform: scaleY(0.5); transform: scaleZ(0.3); transform: skew(30deg, 20deg); transform: skewX(30deg); transform: skewY(1.07rad); /* Multiple function values */ transform: translateX(10px) rotate(10deg) translateY(5px); transform: perspective(500px) translate(10px, 0, 20px) rotateY(3deg); /* Global values */ transform: inherit; transform: initial; transform: revert; transform: revert-layer; transform: unset; 

The transform property may be specified as either the keyword value none or as one or more values.

Читайте также:  Red colors html codes

If perspective() is one of multiple function values, it must be listed first.

Values

One or more of the CSS transform functions to be applied. The transform functions are multiplied in order from left to right, meaning that composite transforms are effectively applied in order from right to left.

Specifies that no transform should be applied.

Accessibility concerns

Scaling/zooming animations are problematic for accessibility, as they are a common trigger for certain types of migraine. If you need to include such animations on your website, you should provide a control to allow users to turn off animations, preferably site-wide.

Also, consider making use of the prefers-reduced-motion media feature — use it to write a media query that will turn off animations if the user has reduced animation specified in their system preferences.

Formal definition

Initial value none
Applies to transformable elements
Inherited no
Percentages refer to the size of bounding box
Computed value as specified, but with relative lengths converted into absolute lengths
Animation type a transform
Creates stacking context yes

Источник

How To Scale, Crop, Flip, and Filter an Image in CSS

Learn how to use CSS to perform the most common image processing manipulations.

How To Scale, Crop, Flip, and Filter an Image in CSS

On this Page

In this article, you will learn how to perform popular image processing operations in CSS. That is possible thanks to the several features introduced by CSS3, which allow you to change how the images look to end-users. To learn instead about image manipulation operations for other frameworks, you can head on here: React or vanilla JS.

First, let’s delve into how image manipulation works in CSS. Then, let’s finally see the most common CSS image processing operations in action.

How CSS Image Manipulation Work

CSS does not allow you to deal with files, data formats, or data transformation. In other words, CSS cannot change an image on a deep level, yet with CSS, you can determine how a browser displays elements.

As a result, as opposed to what would happen when using an HTML canvas element, no pixel manipulation will be executed behind-the-scene. Therefore, your CSS rules won’t affect the file that represents your image. What changes is how your image is displayed frontend-side.

You can flip, blur, and crop an image in CSS, but when downloading the image with the right-click option, the image saved will always be a copy of the original image file. Read this page from MDN Web Docs, if you want to learn more about this phenomenon.

Prerequisites

The CSS properties you will see are widely based on CSS3 and are not supported by Internet Explorer. To verify if your target browsers support a CSS property, visit MDN Web Docs and explore the Browser compatibility section.

Image Processing in CSS

Let’s look at how to perform scaling, cropping, flipping, and filtering an image in CSS.

Scaling an image with object-fit: scale-down

The object-fit CSS property allows you to define how the content of an HTML element should be resized to fit its container. In particular, scale-down acts as if none or contain were set, depending on which would result in a smaller image.

When it acts like none , the image will keep its original intrinsic size and not be scaled down. On the contrary, when it acts like contain the image will be scaled down to fit the container while maintaining its aspect ratio.

Test this CSS rule in the live demo below:

In particular, this is the CSS rule where the magic happens:

Cropping an image with object-fit and object-position

By employing object-fit in conjunction with object-position , you can show a part of your image, just if it has been cropped. In detail, the object-position CSS property allows you to specify the positioning of your element within its container box. This happens by passing this CSS property a position parameter containing from one to four values. This parameter is what defines the position of the element.

By using object-fit to set how your element should fit its container and by positioning it with object-position , you can show only a part of your image as shown in the live example below:

This is the CSS rule to look attention to:

Flipping an image with transform

The transform CSS property is a powerful tool that gives you the ability to rotate, scale, skew, or translate an element. Specifically, you can flip an image by using the scaleX() and scaleY() transformation functions, or by adopting the rotateX() or rotateY() functions.

scaleX() and scaleY() define a transformation that resizes an HTML element along the x-axis and y-axis, respectively. Both accept a number representing the scaling factor as a parameter. Learn how to flip an image vertically with scaleX() in the example below:

In detail, this is the CSS rule to flip an image vertically:

Similarly, rotateX() and rotateY() define a transformation that rotates an HTML element without deforming it around the horizontal axis and vertical axis, respectively. Both require an angle representing the angle of rotation as a parameter. Now, let’s see how to flip an image vertically with rotateY() in the example below:

Specifically, this is what the CSS rule to flip an image vertically looks like:

Filtering an image with filter

The filter CSS property allows you to apply visual effects on an element. This property provides access to several built-in effects, such as blur() , grayscale() , contrast() , and many others. If required, you can also define your custom image filtering functions.

CSS filters are a powerful tool that is typically used to adjust how an image is displayed by the browser and shown to the end-user. Using them is really easy, as shown in the live demo below:

These are the CSS rules where the filtering operations are defined:

.blurred-image < filter: blur(2px); >.grayscale-image < filter: grayscale(80%); >.high-contrast-image

CSS-Only Image Editor vs PhotoEditor SDK

Image manipulation in CSS is an easy and straightforward way to manipulate how an image is displayed with no effort. On the other hand, you cannot save or export the manipulated images with CSS. This means that it is not possible to implement a file image editor based solely on CSS.

Therefore, you can rely on CSS only if you are interested in changing how your images are rendered by the browser. Conversely, if you are looking for a way to manipulate your images and then export them as files, then you need a much more advanced tool. In this case, a commercial solution like IMG.LY’s Photo Editor SDK will provide you with a complete, fast, and easy-to-use image editor.

Conclusion

Today we learned how to use CSS to control how browsers display images. In detail, we delved into how to scale, crop, flip, and filter an image in CSS. These represent the most common image manipulation operations and allow you to transform your image CSS-side. As we have learned, these operations only determine how your browser renders an image. They do not change an image as a data structure.
This means that it is not possible to create an image editor that allows users to export manipulated images while using only CSS. So, if this is what you were looking for, you should consider adopting a fast, advanced, and ready-to-use solution – such as PhotoEditorSDK . And you can get right into the PhotoEditorSDK or VideoEditorSDK and its myriad integrations by starting with a free trial over here.

Thanks for reading! We hope that you found this article helpful. Feel free to reach out to us on Twitter with any questions, comments, or suggestions.

Источник

scale()

Масштабирует элемент в двумерном пространстве по горизонтали и вертикали или одновременно в двух направлениях. Изменение масштаба может происходить как в большую, так и в меньшую сторону.

Масштабирование с помощью scale(sx, xy) продемонстрировано в табл. 1.

Табл. 1. Масштабирование картинки

transform: scale(1) Исходное изображение.
transform: scale(1.2) Увеличение масштаба в 1,2 раза.
transform: scale(1.2, 1) Увеличение масштаба только по горизонтали в 1,2 раза.
transform: scale(0.5) Уменьшение масштаба в два раза.
transform: scale(-1, 1) Зеркальное отражение по горизонтали.
transform: scale(1, -1) Зеркальное отражение по вертикали.
transform: scale(-1) Зеркальное отражение по горизонтали и вертикали.

Синтаксис

transform: scale(sx); transform: scale(sx, xy);

Синтаксис

Описание Пример
Указывает тип значения.
A && B Значения должны выводиться в указанном порядке. &&
A | B Указывает, что надо выбрать только одно значение из предложенных (A или B). normal | small-caps
A || B Каждое значение может использоваться самостоятельно или совместно с другими в произвольном порядке. width || count
[ ] Группирует значения. [ crop || cross ]
* Повторять ноль или больше раз. [,]*
+ Повторять один или больше раз. +
? Указанный тип, слово или группа не является обязательным. inset?
Повторять не менее A, но не более B раз.
# Повторять один или больше раз через запятую. #

Значения

  • значение больше 1 (например: 1.5) приводит к увеличению масштаба;
  • значение меньше 1 (например: 0.8) приводит к уменьшению масштаба;
  • отрицательное значение (например: -1) зеркально отражает элемент по горизонтали;
  • значение 1 оставляет размер элемента исходным и не даёт видимого эффекта.

Одно значение задаёт масштабирование элемента одновременно по горизонтали и вертикали, с сохранением пропорций сторон элемента. Два значения задают масштаб элемента по горизонтали и вертикали независимо, что может привести к искажению пропорций сторон.

Песочница

Пример

scale()
scale()
scale()

В данном примере при наведении указателя на картинку она плавно увеличивает свой масштаб. Чтобы размеры блока оставались исходными используется свойство overflow со значением hidden .

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

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

  • Recommendation ( Рекомендация ) — спецификация одобрена W3C и рекомендована как стандарт.
  • Candidate Recommendation ( Возможная рекомендация ) — группа, отвечающая за стандарт, удовлетворена, как он соответствует своим целям, но требуется помощь сообщества разработчиков по реализации стандарта.
  • Proposed Recommendation ( Предлагаемая рекомендация ) — на этом этапе документ представлен на рассмотрение Консультативного совета W3C для окончательного утверждения.
  • Working Draft ( Рабочий проект ) — более зрелая версия черновика после обсуждения и внесения поправок для рассмотрения сообществом.
  • Editor’s draft ( Редакторский черновик ) — черновая версия стандарта после внесения правок редакторами проекта.
  • Draft ( Черновик спецификации ) — первая черновая версия стандарта.

Браузеры

В таблице браузеров применяются следующие обозначения.

  • — элемент полностью поддерживается браузером;
  • — элемент браузером не воспринимается и игнорируется;
  • — при работе возможно появление различных ошибок, либо элемент поддерживается с оговорками.

Число указывает версию браузреа, начиная с которой элемент поддерживается.

Рецепты

Источник

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