scale()

scale()

The scale() 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. Its result is a data type.

Try it

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 [-1, 1] range, the element grows along that dimension; when inside, it shrinks. A negative value results in a point reflection in that dimension. The value 1 has no effect.

Note: The scale() function only scales in 2D. To scale in 3D, use scale3d() instead.

Syntax

The scale() function is specified with either one or two values, which represent the amount of scaling to be applied in each direction.

Values

Cartesian coordinates on ℝ^2 Homogeneous coordinates on ℝℙ^2 Cartesian coordinates on ℝ^3 Homogeneous coordinates on ℝℙ^3
( sx 0 0 sy ) ( sx 0 0 0 sy 0 0 0 1 ) ( sx 0 0 0 sy 0 0 0 1 ) ( sx 0 0 0 0 sy 0 0 0 0 1 0 0 0 0 1 )
[sx 0 0 sy 0 0]

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.

Читайте также:  Си шарп методы для массивов

Источник

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 ( Черновик спецификации ) — первая черновая версия стандарта.

Браузеры

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

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

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

Рецепты

Источник

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.

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

Источник

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