CSS 同一个元素上的 translateX 和 translateY?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29648494/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 03:10:44  来源:igfitidea点击:

translateX and translateY on same element?

csscss-transforms

提问by Evanss

Is it possible to apply a CC translate X and Y on the same element?

是否可以在同一个元素上应用 CC 平移 X 和 Y?

If I try this the translateX is overridden by the translateY:

如果我尝试此操作,translateX 将被 translateY 覆盖:

.something { 
        transform: translateX(-50%);
        transform: translateY(-50%);
}

回答by Akshay

You can do something like this

你可以做这样的事情

transform:translate(-50%,-50%);

回答by web-tiki

In your case, you can apply both X and Y translations with the translateproperty :

在您的情况下,您可以使用translate属性同时应用 X 和 Y 翻译:

transform: translate(tx[, ty]) /* one or two <translation-value> values */

transform: translate(tx[, ty]) /* one or two <translation-value> values */

[source: MDN]

[来源:MDN]

for your example, it would look like this :

对于您的示例,它看起来像这样:

.something { 
  transform: translate(-50%,-50%);
}

DEMO:

演示:

div{
  position:absolute;
  top:50%; left:50%;
  width:100px; height:100px;
  transform: translate(-50%,-50%);
  background:tomato;
}
<div></div>



As stated by this answer How to apply multiple transforms in CSS3?you can apply several transforms on the same element by specifying them on the same declaration :

正如此答案所述如何在 CSS3 中应用多个变换?您可以通过在同一个声明中指定它们来对同一个元素应用多个转换:

.something { 
  transform: translateX(-50%) translateY(-50%);
}

回答by joews

You can combine X and Y translates into a single expression:

您可以将 X 和 Y 转换为单个表达式:

transform: translate(10px, 20px); /* translate X by 10px, y by 20px */

And, in general, several transforms into a single rule:

并且,一般来说,几个转换成一个规则:

transform: translateX(10px) translateY(20px) scale(1.5) rotate(45deg);