Evil Closet Monkey Evil Closet Monkey - 4 months ago 11
CSS Question

Using `calc()` vs `transform` when placing elements

Is there a reason one would want to use

calc()
over the
transform
property when placing an element, or vise versa, when the size of the element is known?

For example...

.element {
bottom: 100%;
transform: translateY(-9px);
}


Produces the same results as:

.element {
bottom: calc(100% + 9px);
}


If the size of the element is not known, I see the advantage of using
transform
. However, if the size is known (as above) I can just as easily use
calc()
to adjust.

"
calc()
uses just one line, while
transform
requires two lines"


Fair enough. But (in my case) I'm already using
transform
to adjust along the other axis (because I don't know the initial size), so I could easily combine the
translateY()
and
translateX()
to actually reduce the number of lines.

"Because browser support"

Assume we have full browser support across both solutions.

Is there a standard, or performance situation, that would suggest one solution is better than the other?

Answer

transform is a monster capable of doing much more powerful things than simple translations.

Therefore, it has some collateral effects like establishing a containing block for its descendants, even if they are in a fixed position!

Therefore, as a rule of thumb, when you only want simple translations, I would recommend to avoid transform. I prefer calc(), margins, etc.