Css 2d transforms

Property Values

Value Description Play it
none Defines that there should be no transformation Play it »
matrix(n,n,n,n,n,n) Defines a 2D transformation, using a matrix of six values Play it »
matrix3d
(n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n)
Defines a 3D transformation, using a 4×4 matrix of 16 values
translate(x,y) Defines a 2D translation Play it »
translate3d(x,y,z) Defines a 3D translation
translateX(x) Defines a translation, using only the value for the X-axis Play it »
translateY(y) Defines a translation, using only the value for the Y-axis Play it »
translateZ(z) Defines a 3D translation, using only the value for the Z-axis
scale(x,y) Defines a 2D scale transformation Play it »
scale3d(x,y,z) Defines a 3D scale transformation
scaleX(x) Defines a scale transformation by giving a value for the X-axis Play it »
scaleY(y) Defines a scale transformation by giving a value for the Y-axis Play it »
scaleZ(z) Defines a 3D scale transformation by giving a value for the Z-axis
rotate(angle) Defines a 2D rotation, the angle is specified in the parameter Play it »
rotate3d(x,y,z,angle) Defines a 3D rotation
rotateX(angle) Defines a 3D rotation along the X-axis Play it »
rotateY(angle) Defines a 3D rotation along the Y-axis Play it »
rotateZ(angle) Defines a 3D rotation along the Z-axis Play it »
skew(x-angle,y-angle) Defines a 2D skew transformation along the X- and the Y-axis Play it »
skewX(angle) Defines a 2D skew transformation along the X-axis Play it »
skewY(angle) Defines a 2D skew transformation along the Y-axis Play it »
perspective(n) Defines a perspective view for a 3D transformed element
initial Sets this property to its default value. Read about initial
inherit Inherits this property from its parent element. Read about inherit

Значения свойства

Значение Описание
none Преобразование не применяется.
matrix(n,n,n,n,n,n) Применяет 2D преобразование с помощью матрицы из шести значений.
matrix3d(n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n) Применяет 3D преобразование с помощью матрицы из шестнадцати(4х4) значений.
translate(x,y) Функция translate позволяет перемещать элементы влево, вправо, вверх или вниз. Эта функция аналогична поведению position: relative; При использовании этой функции, можно сдвигать элементы не влияя на поток документа.
translate3d(x,y,z) Применяет 3D смещение.
translateX(x) Определяет смещение, только по оси Х.
translateY(y) Определяет смещение, только по оси У.
translateZ(z) Определяет 3D смещение, только по оси Z.
scale(x,y) Функция scale(x,y) масштабирует элемент горизонтально и вертикально. Если указано только одно значение, оно будет использовано сразу и для горизонтального масштабирования и для вертикального. Например, scale(1) оставит элемент такого же размера, scale(2) удвоит его пропорции, scale(0.5) уменьшит элемент в 2 раза и так далее. Предоставление различных значений будет искажать элемент.
Масштабируемый элемент будет увеличиваться от своего центра или уменьшаться к нему, другими словами центр элемента будет всегда находится в одной и той же точке, не зависимо от его размера. Таково поведение элемента по умолчанию, чтобы изменить это можно воспользоваться свойством transform-origin.
scale3d(x,y,z) Применяет 3D преобразование масштаба.
scaleX(x) Определяет преобразование масштаба по оси Х.
scaleY(y) Определяет преобразование масштаба по оси У.
scaleZ(z) Определяет 3D преобразование масштаба по оси Z.
rotate(angle) Функция rotate() поворачивает элемент вокруг точки происхождения по заданному значению угла. Как и в случае с функцией scale(), по умолчанию точка происхождения — это центр элемента.
rotate3d(x,y,z,angle) Определяет 3D поворот.
rotateX(angle) Определяет 3D поворот вдоль оси Х.
rotateY(angle) Определяет 3D поворот вдоль оси У.
rotateZ(angle) Определяет 3D поворот вдоль оси Z.
skew(x, y) Функция skew(x, y) определяет наклон по осям X и Y. Как и следовало ожидать, x определяет наклон оси X,а y определяет наклон оси Y. Если второй параметр опущен, то перекос элемента произойдёт только по оси X.
skewX(angle) Определяет 2D преобразование наклона вдоль оси Х.
skewY(angle) Определяет 2D преобразование наклона вдоль оси У.
perspective(n) Определяет перспективу для преобразования 3D элемента.
inherit Указывает, что значение наследуется от родительского элемента.

Пример

CSS Свойство:

transform:

Результат:

Демонстрация работы свойтсва transform.

CSS Код:

#myDIV { background-color: lightblue; transform: rotate(10deg); }

Кликните на любое значение свойства, чтобы увидеть результат

Управление регистром букв: text-transform

Иногда возникает необходимость вывести слова или первые символы слов с заглавной буквы. В CSS для управления регистром буквы есть свойство .

Дефолтное значение равно , то есть по умолчанию регистр букв не изменяется.

Значение

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

Разметка:

Стили:

Отметьте, что не следует традиционным правилам — оно делает заглавными первые буквы всех слов, включая предлоги. И если вы хотите следовать нормам английского языка, вам придется делать это вручную.

Значение

Если ваша цель — сделать все буквы заглавными, то подходящим значением будет :

Разметка:

Стили:

Значение

Это значение наоборот делает все символы строчными. Естественно, оно не оказывает никакого воздействия на уже имеющиеся строчные буквы.

Разметка:

Стили:

Значение

Это значение появилось в спецификации недавно. Это значение ограничивает символ внутри квадрата, аналогично иероглифам. И применение этого свойство облегчает выравнивание латинских символов с идеографическими.

Не у всех символов есть соответствующая форма, и, значит, не на все символы будет влиять это значение:

Разметка:

Стили:

Это свойство на данный момент поддерживается только в Firefox.

Дополнительная информация

Браузеры отлично поддерживают свойство , у всех основных браузеров с ним нет проблем.

Единственное исключение это значение , которое работает пока только в Firefox. И такая непопулярность вполне может повлечь исключение этого значения из спецификаций.

Также есть небольшое отличие в обработке у Firefox и остальных браузеров.

Вот, например, Firefox:

Заметьте, что первая буква после дефиса не капитализируется. А вот тот же самый пример в Chrome:

В Chrome не делается исключений для первых букв после дефисов — они переводятся в заглавный регистр также как остальные. И это является дефолтным поведением для всех браузеров, кроме упомянутого выше Firefox.

И, наконец, не забывайте о каскадировании. Задание свойства для элемента-контейнера будет унаследовано всеми его потомками. Чтобы избежать неожиданных результатов, задавайте дочерним элементам в значение .

The matrix() Method

The method combines all the 2D transform methods into one.

The matrix() method take six parameters, containing mathematic functions,
which allows you to rotate, scale, move (translate), and skew elements.

The parameters are as follow: matrix(scaleX(),skewY(),skewX(),scaleY(),translateX(),translateY())

Example

div
{
 
transform: matrix(1, -0.3, 0, 1, 0, 0);}

CSS Transform Properties

The following table lists all the 2D transform properties:

Property Description
transform Applies a 2D or 3D transformation to an element
transform-origin Allows you to change the position on transformed elements

CSS 2D Transform Methods

Function Description
matrix(n,n,n,n,n,n) Defines a 2D transformation, using a matrix of six values
translate(x,y) Defines a 2D translation, moving the element along the X- and the Y-axis
translateX(n) Defines a 2D translation, moving the element along the X-axis
translateY(n) Defines a 2D translation, moving the element along the Y-axis
scale(x,y) Defines a 2D scale transformation, changing the elements width and height
scaleX(n) Defines a 2D scale transformation, changing the element’s width
scaleY(n) Defines a 2D scale transformation, changing the element’s height
rotate(angle) Defines a 2D rotation, the angle is specified in the parameter
skew(x-angle,y-angle) Defines a 2D skew transformation along the X- and the Y-axis
skewX(angle) Defines a 2D skew transformation along the X-axis
skewY(angle) Defines a 2D skew transformation along the Y-axis

❮ Previous
Next ❯

CSS Reference

CSS ReferenceCSS Browser SupportCSS SelectorsCSS FunctionsCSS Reference AuralCSS Web Safe FontsCSS Font CombinationsCSS AnimatableCSS UnitsCSS PX-EM ConverterCSS ColorsCSS Color ValuesCSS Default ValuesCSS Entities

CSS Properties

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

backface-visibility
background
background-attachment
background-blend-mode
background-clip
background-color
background-image
background-origin
background-position
background-repeat
background-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-image-outset
border-image-repeat
border-image-slice
border-image-source
border-image-width
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
break-after
break-before
break-inside

caption-side
caret-color
@charset
clear
clip
clip-path
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-face
font-family
font-feature-settings
font-kerning
font-size
font-size-adjust
font-stretch
font-style
font-variant
font-variant-caps
font-weight

grid
grid-area
grid-auto-columns
grid-auto-flow
grid-auto-rows
grid-column
grid-column-end
grid-column-gap
grid-column-start
grid-gap
grid-row
grid-row-end
grid-row-gap
grid-row-start
grid-template
grid-template-areas
grid-template-columns
grid-template-rows

hanging-punctuation
height
hyphens
@import
isolation
justify-content
@keyframes
left
letter-spacing

line-height
list-style
list-style-image
list-style-position
list-style-type

margin
margin-bottom
margin-left
margin-right
margin-top
max-height
max-width
@media
min-height
min-width
mix-blend-mode

object-fit
object-position
opacity
order
outline
outline-color
outline-offset
outline-style
outline-width
overflow
overflow-x
overflow-y

padding
padding-bottom
padding-left
padding-right
padding-top
page-break-after
page-break-before
page-break-inside
perspective
perspective-origin
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-style
text-indent
text-justify
text-overflow
text-shadow
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
width
word-break
word-spacing
word-wrap
writing-mode

z-index

CSS Reference

CSS ReferenceCSS Browser SupportCSS SelectorsCSS FunctionsCSS Reference AuralCSS Web Safe FontsCSS AnimatableCSS UnitsCSS PX-EM ConverterCSS ColorsCSS Color ValuesCSS Default ValuesCSS Entities

CSS Properties

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

backface-visibility
background
background-attachment
background-blend-mode
background-clip
background-color
background-image
background-origin
background-position
background-repeat
background-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-image-outset
border-image-repeat
border-image-slice
border-image-source
border-image-width
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
break-after
break-before
break-inside

caption-side
caret-color
@charset
clear
clip
clip-path
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-face
font-family
font-feature-settings
font-kerning
font-size
font-size-adjust
font-stretch
font-style
font-variant
font-variant-caps
font-weight

grid
grid-area
grid-auto-columns
grid-auto-flow
grid-auto-rows
grid-column
grid-column-end
grid-column-gap
grid-column-start
grid-gap
grid-row
grid-row-end
grid-row-gap
grid-row-start
grid-template
grid-template-areas
grid-template-columns
grid-template-rows

hanging-punctuation
height
hyphens
@import
isolation
justify-content
@keyframes
left
letter-spacing

line-height
list-style
list-style-image
list-style-position
list-style-type

margin
margin-bottom
margin-left
margin-right
margin-top
max-height
max-width
@media
min-height
min-width
mix-blend-mode

object-fit
object-position
opacity
order
outline
outline-color
outline-offset
outline-style
outline-width
overflow
overflow-x
overflow-y

padding
padding-bottom
padding-left
padding-right
padding-top
page-break-after
page-break-before
page-break-inside
perspective
perspective-origin
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-style
text-indent
text-justify
text-overflow
text-shadow
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
width
word-break
word-spacing
word-wrap
writing-mode

z-index

CSS 2D Transform Methods

Function Description
matrix(n,n,n,n,n,n) Defines a 2D transformation, using a matrix of six values
translate(x,y) Defines a 2D translation, moving the element along the X- and the Y-axis
translateX(n) Defines a 2D translation, moving the element along the X-axis
translateY(n) Defines a 2D translation, moving the element along the Y-axis
scale(x,y) Defines a 2D scale transformation, changing the elements width and height
scaleX(n) Defines a 2D scale transformation, changing the element’s width
scaleY(n) Defines a 2D scale transformation, changing the element’s height
rotate(angle) Defines a 2D rotation, the angle is specified in the parameter
skew(x-angle,y-angle) Defines a 2D skew transformation along the X- and the Y-axis
skewX(angle) Defines a 2D skew transformation along the X-axis
skewY(angle) Defines a 2D skew transformation along the Y-axis

❮ Previous
Next ❯

JavaScript

JS Array
concat()
constructor
copyWithin()
entries()
every()
fill()
filter()
find()
findIndex()
forEach()
from()
includes()
indexOf()
isArray()
join()
keys()
length
lastIndexOf()
map()
pop()
prototype
push()
reduce()
reduceRight()
reverse()
shift()
slice()
some()
sort()
splice()
toString()
unshift()
valueOf()

JS Boolean
constructor
prototype
toString()
valueOf()

JS Classes
constructor()
extends
static
super

JS Date
constructor
getDate()
getDay()
getFullYear()
getHours()
getMilliseconds()
getMinutes()
getMonth()
getSeconds()
getTime()
getTimezoneOffset()
getUTCDate()
getUTCDay()
getUTCFullYear()
getUTCHours()
getUTCMilliseconds()
getUTCMinutes()
getUTCMonth()
getUTCSeconds()
now()
parse()
prototype
setDate()
setFullYear()
setHours()
setMilliseconds()
setMinutes()
setMonth()
setSeconds()
setTime()
setUTCDate()
setUTCFullYear()
setUTCHours()
setUTCMilliseconds()
setUTCMinutes()
setUTCMonth()
setUTCSeconds()
toDateString()
toISOString()
toJSON()
toLocaleDateString()
toLocaleTimeString()
toLocaleString()
toString()
toTimeString()
toUTCString()
UTC()
valueOf()

JS Error
name
message

JS Global
decodeURI()
decodeURIComponent()
encodeURI()
encodeURIComponent()
escape()
eval()
Infinity
isFinite()
isNaN()
NaN
Number()
parseFloat()
parseInt()
String()
undefined
unescape()

JS JSON
parse()
stringify()

JS Math
abs()
acos()
acosh()
asin()
asinh()
atan()
atan2()
atanh()
cbrt()
ceil()
clz32()
cos()
cosh()
E
exp()
expm1()
floor()
fround()
LN2
LN10
log()
log10()
log1p()
log2()
LOG2E
LOG10E
max()
min()
PI
pow()
random()
round()
sign()
sin()
sqrt()
SQRT1_2
SQRT2
tan()
tanh()
trunc()

JS Number
constructor
isFinite()
isInteger()
isNaN()
isSafeInteger()
MAX_VALUE
MIN_VALUE
NEGATIVE_INFINITY
NaN
POSITIVE_INFINITY
prototype
toExponential()
toFixed()
toLocaleString()
toPrecision()
toString()
valueOf()

JS OperatorsJS RegExp
constructor
compile()
exec()
g
global
i
ignoreCase
lastIndex
m
multiline
n+
n*
n?
n{X}
n{X,Y}
n{X,}
n$
^n
?=n
?!n
source
test()
toString()

(x|y)
.
\w
\W
\d
\D
\s
\S
\b
\B
\0
\n
\f
\r
\t
\v
\xxx
\xdd
\uxxxx

JS Statements
break
class
continue
debugger
do…while
for
for…in
for…of
function
if…else
return
switch
throw
try…catch
var
while

JS String
charAt()
charCodeAt()
concat()
constructor
endsWith()
fromCharCode()
includes()
indexOf()
lastIndexOf()
length
localeCompare()
match()
prototype
repeat()
replace()
search()
slice()
split()
startsWith()
substr()
substring()
toLocaleLowerCase()
toLocaleUpperCase()
toLowerCase()
toString()
toUpperCase()
trim()
valueOf()

Свойство word-wrap

В HTML для разделения строк существует специальный тег <br>. Но его слишком частое использование считается среди разработчиков дурным тоном и зачастую свидетельствует о непрофессионализме. Как доказательство, представьте, что у вас есть логотип и вы хотите, чтобы каждая буква начиналась с новой строки:

Получился громоздкий и уродливый код, от которого у любого разработчика случится культурный шок. И как поступить, если вы захотите, чтобы в десктопной версии логотип располагался горизонтально, а при ширине экрана менее 550 пикселей вертикально? Поэтому для настройки внешнего вида элементов всегда используйте каскадные таблицы стилей. Тем более с помощью инструментов CSS перенос строки осуществляется более элегантным способом. При этом не возникает избыточной разметки, которая только уменьшает скорость загрузки страниц.

Первое свойство, к которому стоит обратиться для обработки текста, — это word-wrap. Принимает три значения: normal, break-all и keep-all. Вам для работы понадобится запомнить только break-all. Normal стоит по умолчанию, и его нет смысла указывать. Keep-all означает в документе CSS запрет переноса строки. Разработано специально для китайских, японских и корейских иероглифов. Поэтому, если вы не собираетесь вести блог на каком-то из этих языков, свойство вам не пригодится. А также оно не поддерживается браузером Safari и мобильными телефонами на базе iOS.

Чтобы логотипу из предыдущего примера назначить с помощью CSS перенос на новую строку каждой буквы, нужно прописать следующий код:

Ширина и размер шрифта подбирается таким образом, чтобы места хватало только для одной буквы. Word-wrap со значением break-all сообщает браузеру, что слово нужно каждый раз переносить на новую строку. Незаменимым это свойство назвать нельзя. Но оно пригодится при оформлении небольших блоков с текстом, например полей для ввода комментариев.

Examples of uppercase in a Sentence

Recent Examples on the Web: Adjective The Globe explained that the word has evolved from a description of a person’s skin color to signify a race and culture, and deserves the uppercase treatment, much like Latinos get.

David Bauder, The Christian Science Monitor, «What’s in a word? US newsrooms move to capitalize ‘Black.’,» 16 June 2020 It’s also supposed to be lowercase, not uppercase, according to the Associated Press.

Doyle Rice, USA TODAY, «Daylight saving time begins Sunday. Are you ready to spring forward?,» 4 Mar. 2020 The company’s new corporate logo is its name in all uppercase letters.

Washington Post, «Move fast and capitalize things: Facebook unveils new logo,» 5 Nov. 2019 It’s also supposed to be lowercase, not uppercase, according to the Associated Press stylebook.
3.

Doyle Rice, USA TODAY, «10 things you didn’t know about daylight saving time,» 6 Mar. 2018 It’s also supposed to be lowercase, not uppercase, according to the Associated Press stylebook.
3.

Doyle Rice, USA TODAY, «10 things you didn’t know about daylight saving time,» 6 Mar. 2018 Recent Examples on the Web: Noun Choose from four metals — 14k yellow gold or rose plated silver, sterling silver and 14k yellow gold — and customize either both or your right earring with up to ten uppercase letters for each hoop.

Nicole Saunders, NBC News, «Best personalized gift ideas 2020: Unique gift guide,» 17 Nov. 2020 The word black is already our preferred term; the change to uppercase recognizes Black people as a distinct cultural group and puts Black on equal footing with Latino and Native American.

Mike Wilson, Dallas News, «Capitalizing ‘Black’ a sign of respect, changing times,» 24 June 2020 Though Facebook says its new design is aimed at clarity, de Bartolo says all uppercase letters are often less legible than the standard uppercase-lowercase mix.

Washington Post, «Move fast and capitalize things: Facebook unveils new logo,» 5 Nov. 2019 In the last week of December 2018, just eight of the 200 songs on Spotify’s top 200 streaming songs were either all uppercase or all lowercase.

Dan Kopf, Quartzy, «The rise of all-lowercase and all-uppercase song titles,» 21 Aug. 2019 When punctuation counts Google does not recognize uppercase or lowercase letters and punctuation.

Edward C. Baig, USA TODAY, «11 expert tips to search Google better, faster, more strategically,» 2 Nov. 2019 Then there’s the Nutella soufflé, which is neither an uppercase Nutella creation nor a soufflé.

Mike Sutter, ExpressNews.com, «Review: 188 South gives New Braunfels restaurant fans a strong place for pizza, cocktails and small plates,» 28 Nov. 2019 On the Internet, using uppercase letters is shorthand for shouting.

Washington Post, «Move fast and capitalize things: Facebook unveils new logo,» 5 Nov. 2019 In literacy, kindergarten students should know how stories and poems are the same or different; how to identify uppercase and lowercase letters; and how to recognize punctuation marks and many common words.

James Vaznis, BostonGlobe.com, «In Brookline, there’s a worry that kindergarten has lost its joy,» 9 July 2019 Recent Examples on the Web: Noun This post is typed as a shouting tantrum (all upper case) and claims to be written by a man who called corporate headquarters in Charlotte where he was informed of this.

Bill Hand, USA TODAY, «Fact check: NASCAR will not do away with opening prayer, national anthem,» 10 June 2020

Why is capitalization important?

Passwords

Passwords are case-sensitive to add an extra level of security. If your caps lock key is enabled while creating your password, but not when you log in the next day, you won’t be able to access your account.

File names, directories, and paths

When dealing with file names, directories, and paths in many operating systems and paths, they are case-sensitive. For example, in Microsoft Windows nothing is case-sensitive. However, when uploading a file to the Internet, the files and directories become case-sensitive. For example, the file name of this web page is «uppercase.htm» and must be typed in all lowercase in the URL while online. However, if you were viewing the file locally on a Windows computer, the capitalization would not matter.

Measurements

When dealing with computer measurements and other measurements, capitalization is important for identifying the exact type of measurement. For example, «Mb» (short for megabit) and «MB» (short for megabyte) are two different types of measurements with different values.

Commands

Command line commands in operating systems like Linux are case-sensitive, which means if you typed «Ls» to list file you would get an error since the ls command is all lowercase.

Programming functions

In earlier programming languages like FORTRAN, the keywords and the names of data objects needed to be uppercase because punch card machines did not have a Shift key.

Acronyms

To help differentiate an acronym from other words in a sentence, they are typed in uppercase. For example, the acronym RAM is typed in all uppercase to help identify the word as an acronym.

CSS Properties

align-contentalign-itemsalign-selfallanimationanimation-delayanimation-directionanimation-durationanimation-fill-modeanimation-iteration-countanimation-nameanimation-play-stateanimation-timing-functionbackface-visibilitybackgroundbackground-attachmentbackground-blend-modebackground-clipbackground-colorbackground-imagebackground-originbackground-positionbackground-repeatbackground-sizeborderborder-bottomborder-bottom-colorborder-bottom-left-radiusborder-bottom-right-radiusborder-bottom-styleborder-bottom-widthborder-collapseborder-colorborder-imageborder-image-outsetborder-image-repeatborder-image-sliceborder-image-sourceborder-image-widthborder-leftborder-left-colorborder-left-styleborder-left-widthborder-radiusborder-rightborder-right-colorborder-right-styleborder-right-widthborder-spacingborder-styleborder-topborder-top-colorborder-top-left-radiusborder-top-right-radiusborder-top-styleborder-top-widthborder-widthbottombox-decoration-breakbox-shadowbox-sizingbreak-afterbreak-beforebreak-insidecaption-sidecaret-color@charsetclearclipclip-pathcolorcolumn-countcolumn-fillcolumn-gapcolumn-rulecolumn-rule-colorcolumn-rule-stylecolumn-rule-widthcolumn-spancolumn-widthcolumnscontentcounter-incrementcounter-resetcursordirectiondisplayempty-cellsfilterflexflex-basisflex-directionflex-flowflex-growflex-shrinkflex-wrapfloatfont@font-facefont-familyfont-feature-settingsfont-kerningfont-sizefont-size-adjustfont-stretchfont-stylefont-variantfont-variant-capsfont-weightgridgrid-areagrid-auto-columnsgrid-auto-flowgrid-auto-rowsgrid-columngrid-column-endgrid-column-gapgrid-column-startgrid-gapgrid-rowgrid-row-endgrid-row-gapgrid-row-startgrid-templategrid-template-areasgrid-template-columnsgrid-template-rowshanging-punctuationheighthyphens@importisolationjustify-content@keyframesleftletter-spacingline-heightlist-stylelist-style-imagelist-style-positionlist-style-typemarginmargin-bottommargin-leftmargin-rightmargin-topmax-heightmax-width@mediamin-heightmin-widthmix-blend-modeobject-fitobject-positionopacityorderoutlineoutline-coloroutline-offsetoutline-styleoutline-widthoverflowoverflow-xoverflow-ypaddingpadding-bottompadding-leftpadding-rightpadding-toppage-break-afterpage-break-beforepage-break-insideperspectiveperspective-originpointer-eventspositionquotesresizerightscroll-behaviortab-sizetable-layouttext-aligntext-align-lasttext-decorationtext-decoration-colortext-decoration-linetext-decoration-styletext-indenttext-justifytext-overflowtext-shadowtext-transformtoptransformtransform-origintransform-styletransitiontransition-delaytransition-durationtransition-propertytransition-timing-functionunicode-bidiuser-selectvertical-alignvisibilitywhite-spacewidthword-breakword-spacingword-wrapwriting-modez-index

Смещение translate()

Очень удобное свойство, которое позволяет смещать элементы, которые не позиционированы абсолютно или относительно. В качестве аргументов можно указывать число в %, px, em, rem и т.п., причем как положительные, так и отрицательные. В случае использования % величина смещения берется от ширины или высоты элемента.

При использовании функции translate() с одним параметром смещение будет происходить по горизонтали (вправо — при положительных значениях, влево — при отрицательных значениях). Можно указать 2 параметра — тогда смещение будет и по горизонтали, и по вертикали одновременно. Для того чтобы сместить элемент по одной из осей, можно использовать функции  translateX() или  translateY() для горизонтального и вертикального смещения:

transform: translate()

.box1 {
transform: translate(-45px);
}
.box2 {
transform: translate(20%, 20%);
}
.box3 {
transform: translateX(2em);
}
.box4 {
transform: translateY(3rem);
}
.box5 {
transition: transform .7s;
}
.box5:hover {
transform: translate(3rem, 2em);
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

.box1{

transformtranslate(-45px);

}

.box2{

transformtranslate(20%,20%);

}

.box3{

transformtranslateX(2em);

}

.box4{

transformtranslateY(3rem);

}

.box5{

transitiontransform.7s;

}

.box5hover{

transformtranslate(3rem,2em);

}

See the Pen CSS-property transform: translate() by Elen (@ambassador) on CodePen.dark

Трехмерный сдвиг элементов

Следующая функция — translate3d() позволяет нам задать трехмерное преобразование путем сдвига элемента, используя координаты трёх осей (X,Y и Z). Перейдем к примеру:

<!DOCTYPE html>
<html>
<head>
	<meta charset = "UTF-8">
	<title>Трехмерный сдвиг элементов</title>
<style>
.static {
display: inline-block; /* блочно-строчные элементы (выстраиваем элементы в линейку) */
margin: 10px; /* внешние отступы со всех сторон */
background: gray; /* цвет заднего фона */
}
div {
width: 180px; /* ширина элемента */
height: 100px; /* высота элемента */
line-height: 100px; /* высота строки (выраывниваем по вертикали) */
text-align: center; /* горизонтальное выравнивание текста по центру */
transition: 0.2s; /* переходный эффект составляет 200 миллисекунд (0,2 секунды) */
}
.test2, .test4, .test6 {background: orange;} /* цвет заднего фона */
.test, .test3, .test5 {background: plum;} /* цвет заднего фона */
.test:hover {
transform: perspective(500px) rotateX(45deg) translate3d(20px,20px,20px); /* используем несколько функций преобразования для элемента при наведении (перспектива, поворот по оси X, трехмерный сдвиг элемента) */
}
.test2:hover {
transform: perspective(500px) rotateX(45deg) translate3d(-20px,-20px,-20px); /* используем несколько функций преобразования для элемента при наведении (перспектива, поворот по оси X, трехмерный сдвиг элемента) */
}
.test3:hover {
transform: perspective(500px) rotateX(45deg) translate3d(-20px,-20px,-80px); /* используем несколько функций преобразования для элемента при наведении (перспектива, поворот по оси X, трехмерный сдвиг элемента) */
}
.test4:hover {
transform: perspective(500px) rotateX(45deg) translate3d(0,0,-80px); /* используем несколько функций преобразования для элемента при наведении (перспектива, поворот по оси X, трехмерный сдвиг элемента) */
}
.test5:hover {
transform: perspective(500px) rotateX(45deg) translate3d(20px,0, 40px); /* используем несколько функций преобразования для элемента при наведении (перспектива, поворот по оси X, трехмерный сдвиг элемента) */
}
.test6:hover {
transform: perspective(500px) rotateX(45deg) translate3d(0,20px, 40px); /* используем несколько функций преобразования для элемента при наведении (перспектива, поворот по оси X, трехмерный сдвиг элемента) */
}
</style>
</head>
	<body>
		<div class = "static"><div class = "test">translate3d(20px,20px,20px)*</div></div>
		<div class = "static"><div class = "test2">translate3d(-20px,-20px,-20px)*</div></div>
		<div class = "static"><div class = "test3">translate3d(-20px,-20px,-80px)*</div></div><br>
		<div class = "static"><div class = "test4">translate3d(0,0,-80px)*</div></div>
		<div class = "static"><div class = "test5">translate3d(20px,0, 40px)*</div></div>
		<div class = "static"><div class = "test6">translate3d(0,20px, 40px)*</div></div>
	</body>
</html>

По аналогии с ранее рассмотренными функциями сдвига элементов, функция translate3d() задаёт сдвиг одновременно по осям X,Y и Z. Первое значение функции определяет горизонтальный сдвиг элемента (положительное значение сдвигает элемент вправо по оси X, а отрицательное влево по оси X). Второе значение функции определяет вертикальный сдвиг элемента (положительное значение сдвигает элемент вниз по оси Y, а отрицательное вверх по оси Y). Третее значение функции определяет сдвиг по оси Z (отрицательное значение отдаляет элемент). Если указать значение 0 для любой оси, то элемент не будет по ней сдвигаться, по аналогии с другими функциями.

Результат нашего примера:

Рис. 183 Пример трехмерного сдвига элементов (функция преобразования элемента translate3d).

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector