How to apply multiple transforms in CSS?

2019-01-01 03:26发布

Using CSS, how can I apply more than one transform?

Example: In the following, only the translation is applied, not the rotation.

li:nth-child(2) {
    transform: rotate(15deg);
    transform: translate(-20px,0px);        
}

9条回答
春风洒进眼中
2楼-- · 2019-01-01 03:58

Just start from there that in CSS, if you repeat 2 values or more, always last one gets applied, unless using !important tag, but at the same time avoid using !important as much as you can, so in your case that's the problem, so the second transform override the first one in this case...

So how you can do what you want then?...

Don't worry, transform accepts multiple values at the same time... So this code below will work:

li:nth-child(2) {
  transform: rotate(15deg) translate(-20px, 0px); //multiple
}

If you like to play around with transform run the iframe from MDN below:

<iframe src="https://interactive-examples.mdn.mozilla.net/pages/css/transform.html" class="interactive  " width="100%" frameborder="0" height="250"></iframe>

Look at the link below for more info:

<< CSS transform >>

查看更多
冷夜・残月
3楼-- · 2019-01-01 04:00

Some time in the future, we can write it like this:

li:nth-child(2) {
    rotate: 15deg;
    translate:-20px 0px;        
}

This will become especially useful when applying individual classes on an element:

<div class="teaser important"></div>

.teaser{rotate:10deg;}
.important{scale:1.5 1.5;}

This syntax is defined in the in-progress CSS Transforms Level 2 specification, but can't find anything about current browser support other then chrome canary. Hope some day i'll come back and update browser support here ;)

Found the info in this article which you might want to check out regarding workarounds for current browsers.

查看更多
高级女魔头
4楼-- · 2019-01-01 04:05

A simple way to apply multiple transform is this

li:nth-of-type(2){
    transform : translate(-20px, 0px) rotate(15deg);
}

But also don't forget that you need to add prefix to let it work in all browsers as some browers like safari, IE not support tranform property without prefix.

li:nth-of-type(2){
    transform : translate(-20px, 0px) rotate(15deg);
    -moz-transform : translate(-20px, 0px) rotate(15deg);
    -webkit-transform : translate(-20px, 0px) rotate(15deg);
    -o-transform : translate(-20px, 0px) rotate(15deg);
    -ms-transform : translate(-20px, 0px) rotate(15deg);
}
查看更多
登录 后发表回答