100

I would like to be able to use calc() with transform:translateX in my CSS.

E.g.,

#myDiv {
  -webkit-transform: translateX(calc(100% - 50px));
  -moz-transform: translateX(calc(100% - 50px));
  transform: translateX(calc(100% - 50px));
}

While this works perfectly in Chrome, Safari, and Firefox - it does not work in IE10 or IE11.

You can see a simple example here: http://jsfiddle.net/SL2mk/9/

Is this impossible? Is it a bug in IE, or is calc() not supposed to work in this context?

For what it's worth - I read here that you can "stack" translateX to acheive the same effect, and my testing seems to confirm this. I.e.,

#div {
  transform: translateX(calc(100% - 50px));
}

is the same as:

#div {
  transform: translateX(100%) translateX(-50px);
}

But I don't know if this is the best, most reliable, and future-proof way to do this.

I also know that it's possible to use left instead of translateX, but the latter is much smoother when used with transitions, since, as I understand it, it forces the use of the GPU to handle the animation.

1

2 Answers 2

245

This:

transform: translateX(100%) translateX(-50px);

gets compiled at parse time, but calc expression here :

transform: translateX(calc(100% - 50px));

has to be interpreted each time when browser needs that value. Result of the expression can be cached but I wouldn't rely on browsers to use such kind of optimizations.

So first one is better in the sense that a) it works now, b) is effective and c) it will work in future until the spec will be in effect.

8
  • This was a great workaround to an issue I was having with the YUI CSS compressor not handling a nested calc() expression correctly. Thanks! May 10, 2016 at 18:50
  • 24
    This is by far the most helpful thing I've learned in a long time about CSS!
    – nirazul
    May 13, 2016 at 19:32
  • Wow, this is peculiar! It worked really well for me. Thank you. Sep 26, 2016 at 10:30
  • 11
    Its silly, but the new information for me here is that is possible to use same type of transforms multiple times on an element! Thanks!
    – marcias
    Dec 15, 2016 at 16:53
  • 2
    are the 2 translateX executed at the same time or one after another? Because, if one after another, also transitions properties would dubled, causing different effect than calc() usage. Oct 27, 2018 at 12:30
11

I just use them both with -ms- browser selector. It works perfectly.

-ms-transform: translateX(100%) translateX(-50px); /* IE 11 */
transform: translateX(calc(100% - 50px));
1
  • 1
    i confirm this works decently well. (i'm actually using something like calc(912px - 50vw) to prevent a sidebar from displaying on top of a dashboard unless you hover it.
    – GottZ
    May 2, 2019 at 20:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.