Translate X and Y percentage values based on elements height and width?

When using percentage in a transform translate on a non-SVG element, it refers to the width or height of itself. Take a look at https://davidwalsh.name/css-vertical-center (demo):

One interesting thing about CSS transforms is that, when applying them with percentage values, they base that value on the dimensions of the element which they are being implemented on, as opposed to properties like top, right, bottom, left, margin, and padding, which only use the parent’s dimensions (or in case of absolute positioning, which uses its closest relative parent).

On an SVG element, a transform percentage refers to the size of the parent instead!

Here is a pen:

https://codepen.io/trusktr/pen/gOdwWXv

svg, [outer] {
  border: 1px solid black;
}

rect {
  transform: translate3d(50%, 50%, 0);
}

[inner] {
  background: black;
  transform: translate3d(50%, 50%, 0);
}
<svg width="100" height="80">
    <rect width="20" height="20" />
</svg>

<div outer style="width: 100px; height: 80px;">
    <div inner style="width: 20px; height: 20px;"></div>
</div>

Strange, huh?

Leave a Comment