Nicholas Pappas
Nicholas Pappas

Reputation: 10624

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?

Upvotes: 0

Views: 336

Answers (2)

Oriol
Oriol

Reputation: 288600

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.

Upvotes: 4

Ragdoll
Ragdoll

Reputation: 335

Transforms can be affected by other transforms, which may cause a difference in rendering. For example, if you were using the perspective transform, translateY() would take place inside that perspective. So, the perspective would be applied, and then the element would be transformed according to the vanishing point you set.

If you were using calc(), instead, the element would be positioned on the page irrespective of the set perspective. It’s probably a subtle difference, but it’s there.

If you’re not using a 3D transform like perspective, however, or if translate() is the only transform you’re using, I don’t think there’s a difference.

Upvotes: 2

Related Questions