SyntaxStudy
Sign Up
CSS Intermediate 8 min read

Transform Matrix

Transform Matrix

The matrix() and matrix3d() functions represent all 2D and 3D transforms as a single mathematical matrix. While rarely written by hand, understanding them explains how CSS transforms are calculated internally.

2D Matrix

matrix(a, b, c, d, tx, ty) encodes scale, rotation, skew, and translation into six values. The browser composes all transform functions into a single matrix before rendering.

3D Matrix

matrix3d() uses a 4×4 matrix — 16 values — to encode all 3D transformations including perspective.

Practical Use

The DOMMatrix JavaScript API lets you read, compose, and apply matrices programmatically for animations and draggable interfaces.

Example
/* Equivalent transforms: */

/* Human-readable form */
.readable {
    transform: translateX(50px) translateY(30px) rotate(45deg) scale(1.5);
}

/*
  Matrix equivalent (computed by the browser):
  matrix(a,   b,   c,   d,   tx,  ty)
  matrix(scaleX*cos, scaleY*sin, -scaleX*sin, scaleY*cos, tx, ty)
*/
.matrix {
    /* rotate(45deg) scale(1.5) translate(50px, 30px) */
    transform: matrix(
        1.0607,   1.0607,
       -1.0607,   1.0607,
        50,       30
    );
}

/* Reading transform via JS DOMMatrix */
/*
  const el = document.querySelector(".box");
  const m = new DOMMatrix(
    getComputedStyle(el).transform
  );
  console.log(m.m41, m.m42); // tx, ty values
*/

/* Identity matrix — no transformation */
.identity {
    transform: matrix(1, 0, 0, 1, 0, 0);
}
Pro Tip

You will almost never need to write a matrix() value by hand — but reading it from getComputedStyle via the DOMMatrix API is very useful when you need to extract the current translation or scale of an animated element in JavaScript.