64

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

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

.something { 
        transform: translateX(-50%);
        transform: translateY(-50%);
}
web-tiki
  • 99,765
  • 32
  • 217
  • 249
Evanss
  • 23,390
  • 94
  • 282
  • 505
  • possible duplicate of [How to apply multiple transforms in CSS3?](http://stackoverflow.com/questions/10765755/how-to-apply-multiple-transforms-in-css3) – Jeroen Apr 15 '15 at 11:05
  • I understand this is a demo, but just rememeber to include browser prefixing as well – jbutler483 Apr 15 '15 at 11:05
  • 2
    @Jeroen Not a duplicate, this is actually different. – Mathew Thompson Apr 15 '15 at 11:05
  • 2
    @mattytommo Isn't it? Wouldn't `.something { transform: translateX(-50%) translateY(-50%); }` be a solution? – Jeroen Apr 15 '15 at 11:06
  • 3
    @Jeroen It would, but the real answer is the existence of the `translate` property which encompasses both axes, thus removing the need for duplicate properties. – Mathew Thompson Apr 15 '15 at 11:12

3 Answers3

108

You can do something like this

transform:translate(-50%,-50%);
Mathew Thompson
  • 55,877
  • 15
  • 127
  • 148
Akshay
  • 14,138
  • 5
  • 46
  • 70
15

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

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

[source: 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 :

.something { 
  transform: translateX(-50%) translateY(-50%);
}
web-tiki
  • 99,765
  • 32
  • 217
  • 249
8

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

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);
joews
  • 29,767
  • 10
  • 79
  • 91