@eprev
My name’s Anton Eprev and I’m a software engineer working as front-end developer at Booking.com in Amsterdam. Tinker with electronics and 3D printers in spare time. I’m on Twitter, GitHub and Unsplash.

How to detect if CSS transforms are supported on SVG

If you're reading this, then apparently you already know that IE and Edge don’t support CSS transformations on SVG and neither apply CSS transitions. Moreover, SVG animations might not be an option, since Chrome deprecated SMIL in favor of CSS animations. How come? Probably you’re thinking now of using CSS when it’s available and falling back to SVG transform attribute.

So how to check whether or not the browser supports CSS transforms on SVG elements? I came up with the following approach:

const supportsCSSTransformsOnSVG = (() => {
  const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
  svg.setAttribute('viewBox', '0 0 2 2');
  Object.assign(svg.style, {
    position: 'absolute',
    top: 0,
    left: 0,
    width: '2px',
    height: '2px',
  });
  svg.innerHTML = '<rect width="1" height="1" style="transform: translate(1px, 1px)"/>';
  document.body.appendChild(svg);
  const result = document.elementFromPoint(1, 1) !== svg;
  svg.parentNode.removeChild(svg);
  return result;
})();

Which can be used later on:

if (supportsCSSTransformsOnSVG) {
  el.style.transform = `translate(${dx}px, ${dy}px)`;
} else {
  el.setAttribute('transform', `translate(${dx} ${dy})`);
}
Want to leave a comment on this? Visit the post’s issue page on GitHub.