DEV Community

Deekor
Deekor

Posted on

getComputedStyle isn't your CSS: mapping it back to Tailwind v3/v4

I've been working on a style inspector that turns an element's styles into Tailwind classes. The obvious approach is to read getComputedStyle, look each value up in a table and call it done. That falls apart quickly, because the computed style isn't the CSS you wrote. It's what the browser resolved it to.

These are my notes on the gap between the two, plus a simplified version of the mapping. All code below was tested in Node and headless Chrome against real Tailwind v3 and v4 output; Firefox and Safari are untested.

What getComputedStyle returns

const cs = getComputedStyle(el);
cs.getPropertyValue('padding-top'); // "24px"
cs.color;                           // "rgb(26, 43, 60)"
getComputedStyle(el, '::before').content; // pseudo-elements too
Enter fullscreen mode Exit fullscreen mode

Here's what Chrome returns for one element:

Authored Computed
padding: 1.5rem 13px padding-top: 24px, padding-left: 13px
font-size: 0.875em (parent 16px) 14px
width: 50% (parent 400px) 200px
margin: 0 auto margin-left: 87px
background: hsl(217 91% 60%) rgb(60, 131, 246)
line-height: normal normal
line-height: 1.5 24px
transform: rotate(45deg) matrix(0.707107, 0.707107, -0.707107, 0.707107, 0, 0)

A few things follow from this:

  • Units are gone. rem, em and % all become px. You can't tell p-4 from p-[16px], and w-1/2 from w-[200px].
  • auto is gone too on a rendered element. Width and margins come back as used pixel values, so mx-auto shows up as two equal numbers. On a display: none element you get auto back instead. Same property, different answer.
  • Unitless line-height becomes px, but normal stays normal. So leading-normal (1.5) and line-height: normal are different things.
  • Colors depend on how they were written. hex, named and hsl() come back as rgb()/rgba(). But oklch(62.3% 0.214 259.815) came back as oklch(0.623 0.214 259.815), and a color-mix(in oklab, ...) came back as oklab(...). That matters a lot for Tailwind v4 (more on that below).
  • Shorthands are unreliable. padding gave me 24px 13px, but I read longhands (padding-top and so on) and rebuild the shorthand myself.
  • Everything has a value. A plain <p> reports font-size: 16px, font-weight: 400, color: rgb(0, 0, 0) and margin-top: 16px from the user-agent stylesheet. If you emit a class for every property, you get garbage like text-base font-normal text-black on every node.

Mapping pixels to the scale

Tailwind's spacing unit is 0.25rem, which is 4px at the default 16px root. (If the page changes the root font size, this whole approach needs that number as a parameter.)

The v3 and v4 rules differ. v3 has a fixed list of steps: p-13 doesn't exist, so 52px has to be p-[52px]. In v4 the spacing utilities are calc(var(--spacing) * N), so p-13 works, and so does p-3.25 for 13px. That's valid, but whether you want it or p-[13px] is a style choice.

// "13px" -> 13, "3.35544e+07px" -> 33554400, anything else -> null
export function toPx(value) {
  const m = /^(-?[\d.]+(?:e[+-]?\d+)?)px$/i.exec(value.trim());
  return m ? Number(m[1]) : null;
}

const V3_STEPS = new Set([0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 5, 6, 7, 8, 9, 10,
  11, 12, 14, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 64, 72, 80, 96]);

export function spacing(prefix, value, version = 4) {
  const n = toPx(value);
  if (n === null) return `${prefix}-[${value}]`; // auto, %, etc.
  const sign = n < 0 ? '-' : '';
  const abs = Math.abs(n);
  if (abs === 1) return `${sign}${prefix}-px`;
  const step = abs / 4; // 0.25rem = 4px at a 16px root
  const ok = version === 4 ? Number.isInteger(abs) : V3_STEPS.has(step);
  return ok ? `${sign}${prefix}-${step}` : `${sign}${prefix}-[${n}px]`;
}
Enter fullscreen mode Exit fullscreen mode

The e+07 in the regex isn't paranoia. v4's rounded-full is calc(infinity * 1px), and Chrome reports it as 3.35544e+07px. In v3 it's 9999px.

Font sizes are the same in v3 and v4 (text-xs is 12px through text-9xl at 128px). Border radii are not: v4 renamed them. 4px is rounded in v3 but rounded-sm in v4, and 2px went from rounded-sm to rounded-xs.

const FONT_SIZES = { 12: 'xs', 14: 'sm', 16: 'base', 18: 'lg', 20: 'xl',
  24: '2xl', 30: '3xl', 36: '4xl', 48: '5xl', 60: '6xl', 72: '7xl',
  96: '8xl', 128: '9xl' };

export function fontSize(value) {
  const n = toPx(value);
  return FONT_SIZES[n] ? `text-${FONT_SIZES[n]}` : `text-[${value}]`;
}

const RADII = {
  3: { 0: 'none', 2: 'sm', 4: '', 6: 'md', 8: 'lg', 12: 'xl', 16: '2xl', 24: '3xl' },
  4: { 0: 'none', 2: 'xs', 4: 'sm', 6: 'md', 8: 'lg', 12: 'xl', 16: '2xl', 24: '3xl', 32: '4xl' },
};

export function radius(value, version = 4) {
  const n = toPx(value);
  if (n !== null && n >= 9999) return 'rounded-full';
  const name = RADII[version][n];
  if (name === undefined) return `rounded-[${value}]`;
  return name ? `rounded-${name}` : 'rounded';
}
Enter fullscreen mode Exit fullscreen mode

Colors: nearest match, not exact match

The v3 palette is hex (blue-500 is #3b82f6). v4 defines it in OKLCH (blue-500 is oklch(62.3% 0.214 259.815)). So a v4 page hands you oklch(...) from getComputedStyle, a v3 page hands you rgb(...), and bg-blue-500/50 in v4 comes back as oklab(0.623 -0.0378409 -0.210628 / 0.5).

I convert everything to OKLab and take the nearest palette entry. OKLab is roughly perceptual, so plain Euclidean distance is a sane metric:

const lin = (c) => (c /= 255) <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;

function rgbToOklab(r, g, b) {
  [r, g, b] = [r, g, b].map(lin);
  const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);
  const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
  const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
  return [
    0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s,
    1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s,
    0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s,
  ];
}

// rgb/rgba/oklch/oklab from getComputedStyle, plus hex from a v3 palette
export function parseColor(str) {
  str = str.trim();
  if (str.startsWith('#')) {
    const h = str.slice(1);
    const full = h.length === 3 ? [...h].map((c) => c + c).join('') : h;
    const [r, g, b] = [0, 2, 4].map((i) => parseInt(full.slice(i, i + 2), 16));
    return { lab: rgbToOklab(r, g, b), alpha: 1 };
  }
  const m = /^(rgba?|oklch|oklab)\(([^)]*)\)$/.exec(str);
  if (!m) return null;
  const nums = m[2].split(/[\s,/]+/).filter(Boolean)
    .map((t) => (t === 'none' ? 0 : t.endsWith('%') ? parseFloat(t) / 100 : parseFloat(t)));
  const [x, y, z, alpha = 1] = nums;
  if (m[1].startsWith('rgb')) return { lab: rgbToOklab(x, y, z), alpha };
  if (m[1] === 'oklab') return { lab: [x, y, z], alpha };
  const h = (z * Math.PI) / 180; // oklch -> oklab
  return { lab: [x, y * Math.cos(h), y * Math.sin(h)], alpha };
}

const dist = (p, q) => Math.hypot(p[0] - q[0], p[1] - q[1], p[2] - q[2]);
const hex = (str) => {
  const m = /^rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(str);
  return m ? '#' + m.slice(1, 4).map((v) => (+v).toString(16).padStart(2, '0')).join('') : null;
};

// palette: { 'blue-500': '#3b82f6' or 'oklch(62.3% 0.214 259.815)', ... }
export function color(prefix, value, palette, maxDist = 0.005) {
  const c = parseColor(value);
  if (!c) return `${prefix}-[${value.replaceAll(' ', '_')}]`;
  if (c.alpha === 0) return `${prefix}-transparent`;
  let best = null;
  let bestD = Infinity;
  for (const [name, v] of Object.entries(palette)) {
    const d = dist(c.lab, parseColor(v).lab);
    if (d < bestD) [best, bestD] = [name, d];
  }
  const opacity = c.alpha < 1 ? `/${Math.round(c.alpha * 100)}` : '';
  if (bestD <= maxDist) return `${prefix}-${best}${opacity}`;
  const raw = c.alpha === 1 && hex(value) ? hex(value) : value.replaceAll(' ', '_');
  return `${prefix}-[${raw}]`;
}
Enter fullscreen mode Exit fullscreen mode

The threshold is a judgment call. hsl(217 91% 60%) lands about 0.003 from blue-500, which is just rounding, so it should snap. #1a2b3c is about 0.008 from slate-800, and I'd rather keep that as bg-[#1a2b3c] than quietly change the design. Note the _ in arbitrary values: Tailwind reads underscores as spaces, so oklch(0.5 0.1 200) has to become bg-[oklch(0.5_0.1_200)].

One more thing the tests turned up: some palette entries are literally the same color. In v3, neutral-50 and zinc-50 are both #fafafa. A computed value can't tell you which name the author used.

Putting it together

function box(cs, prop, prefix, version) {
  const sides = ['top', 'right', 'bottom', 'left'];
  const [t, r, b, l] = sides.map((s) => cs.getPropertyValue(`${prop}-${s}`));
  if (t === r && r === b && b === l) return t === '0px' ? [] : [spacing(prefix, t, version)];
  return [t, r, b, l]
    .map((v, i) => (v === '0px' ? null : spacing(prefix + sides[i][0], v, version)))
    .filter(Boolean);
}

export function toTailwind(el, palette, version = 4) {
  const cs = getComputedStyle(el);
  const parent = el.parentElement && getComputedStyle(el.parentElement);
  const inherited = (prop) => parent && cs.getPropertyValue(prop) === parent.getPropertyValue(prop);
  const out = [...box(cs, 'padding', 'p', version), ...box(cs, 'margin', 'm', version)];
  if (!inherited('font-size')) out.push(fontSize(cs.fontSize));
  if (!inherited('color')) out.push(color('text', cs.color, palette));
  if (cs.backgroundColor !== 'rgba(0, 0, 0, 0)') out.push(color('bg', cs.backgroundColor, palette));
  if (cs.borderTopLeftRadius !== '0px') out.push(radius(cs.borderTopLeftRadius, version));
  return out;
}
Enter fullscreen mode Exit fullscreen mode

The "same as parent" check is crude, but it removes a lot of inherited noise. Here is toTailwind run on elements styled with real compiled Tailwind v4 CSS in headless Chrome:

p-4 text-sm text-slate-700 bg-blue-500 rounded-lg  => p-4 text-sm text-slate-700 bg-blue-500 rounded-lg
px-3 py-1.5 bg-blue-500/50 rounded-full text-2xl   => pt-1.5 pr-3 pb-1.5 pl-3 text-2xl bg-blue-500/50 rounded-full
p-[13px] mt-2 bg-[#1a2b3c] rounded-sm              => p-3.25 mt-2 bg-[#1a2b3c] rounded-sm
Enter fullscreen mode Exit fullscreen mode

Same idea for v3, with the hex palette and version = 3. The second line shows what's still missing: collapsing sides into px/py. That's an easy next step.

Edge cases not covered in this code

  • Transforms. In v3, rotate-45 writes to transform, so you get a matrix(...) back, and turning it back into translate/rotate/scale means decomposing it (not covered in this code). In v4, rotate-45 sets the separate rotate property, so Chrome reports rotate: 45deg and transform: none. Check both.
  • Percentages and auto. Already resolved to pixels by the time you read them. Getting w-1/2 or mx-auto back means looking at the stylesheet rules, not the computed style.
  • em/rem. Same story. If the root font size isn't 16px, the 4px step is wrong.
  • Pseudo-elements. getComputedStyle(el, '::before') works, but the output needs a before: prefix, and content comes back as a quoted string.
  • States and breakpoints. The computed style is only the current state at the current viewport. You'll never see hover: or md: this way.

Where this ended up

This is the problem I'm working on in PeekStyle, a Chrome extension that turns an element's styles into CSS or Tailwind. The shipping version makes some different calls than the code above: it converts oklch/lab/color-mix() to sRGB, only uses a palette class on an exact hex match (otherwise an arbitrary value like bg-[#d6f25c]), and decomposes clean transform matrices when possible. It's not in the Chrome Web Store yet. There's a $15 lifetime pre-order with a 14-day refund, no questions; the first build is expected within ~6 weeks of payment, and if it doesn't ship by then you get a full refund: peekstyle.vercel.app.

If you've found a good way to recover hover/focus states or responsive breakpoints from a live page, I'd like to hear how in the comments.


I'm Evgeny (Deekor), a developer based in Bangkok. More of my projects: deekor.dev

Written with the help of an AI assistant; code and claims checked by me.

Top comments (0)