DEV Community

Alexander
Alexander

Posted on

Automating pixel to rem conversion for Figma typography tokens

You open your browser dev tools and see font-size: 16px on your main heading. You then go into your browser settings and bump the default text size up to 200% for an accessibility test. You switch back to your app. Nothing happens. The text stays exactly the same size. Your entire layout is rigid. This happens because your design tokens export absolute pixel values straight out of Figma.

Designers work in pixels. Figma operates in pixels. But web browsers need relative units like rem to respect user preferences. If you just dump Figma variables into CSS directly, you break accessibility for users who rely on custom text sizes.

We need a way to intercept those pixel values and run some math before they hit our codebase. We can build a small processing pipeline to handle this automatically.

Prerequisites

You will need a basic Node environment for this script. We are going to use Style Dictionary to process a raw JSON file. Make sure you have an empty project ready. Run npm init -y in your terminal to create a package file. Then run npm install style-dictionary to get the core package.

Step 1: The Raw Figma Tokens

Let us look at a typical JSON output from a Figma token export. Create a file called tokens.json in your project root.

{
  "typography": {
    "heading": {
      "large": {
        "fontSize": { "value": "32px", "type": "typography" },
        "lineHeight": { "value": "40px", "type": "typography" }
      },
      "body": {
        "fontSize": { "value": "16px", "type": "typography" },
        "lineHeight": { "value": "24px", "type": "typography" }
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

This is standard stuff. The values are hardcoded pixels. If we generate CSS from this right now, we get absolute sizes that ignore user preferences. We need to catch these values in transit.

Step 2: The Transform Script

Create a new file called build.js. We will write a custom transform function to catch any pixel value and convert it to a rem value.

const StyleDictionary = require('style-dictionary');

const baseFontSize = 16;

StyleDictionary.registerTransform({
  name: 'size/pxToRem',
  type: 'value',
  matcher: function(token) {
    return token.type === 'typography' && token.value.includes('px');
  },
  transformer: function(token) {
    const pixelValue = parseFloat(token.value);
    const remValue = pixelValue / baseFontSize;
    return `${remValue}rem`;
  }
});
Enter fullscreen mode Exit fullscreen mode

So basically we are registering a new rule. The matcher looks for any token categorized as typography. It also checks if the value string contains px. If it matches, the transformer takes over. We parse the number out of the string. We divide it by our base font size of 16. Then we slap rem onto the end. It is a very simple but powerful interception.

Step 3: Handling Line Heights

Line heights can be tricky. Sometimes they are percentages. Sometimes they are pixels. Sometimes they are unitless numbers. We really want unitless numbers for line heights in CSS. It prevents compounding issues on child elements.

Let us add another transform just for line heights to keep things clean.

StyleDictionary.registerTransform({
  name: 'size/lineHeightUnitless',
  type: 'value',
  matcher: function(token) {
    return token.type === 'typography' && token.path.includes('lineHeight');
  },
  transformer: function(token) {
    if (token.value.includes('px')) {
      const pixelValue = parseFloat(token.value);
      const fontSize = 16; 
      return pixelValue / fontSize;
    }
    if (token.value.includes('%')) {
      return parseFloat(token.value) / 100;
    }
    return token.value;
  }
});
Enter fullscreen mode Exit fullscreen mode

This is a simplified version. Tbh you would normally want to divide the line height by its own font size token. But for this example we are just normalizing the math against the base size. It strips the unit and gives us a clean multiplier.

Step 4: Going Further with Fluid Typography

Static rem values are great for basic accessibility. But modern interfaces often require fluid typography. You want that 2rem heading to scale down to 1.5rem on mobile screens automatically. You can do this with CSS clamp() functions.

We can update our transform to generate a clamp function instead of a static rem value. We just need a minimum viewport width and a maximum viewport width.

StyleDictionary.registerTransform({
  name: 'size/fluidClamp',
  type: 'value',
  matcher: function(token) {
    return token.type === 'typography' && token.fluid === true;
  },
  transformer: function(token) {
    const minPx = parseFloat(token.min);
    const maxPx = parseFloat(token.max);
    const minVw = 320;
    const maxVw = 1200;

    const minRem = minPx / 16;
    const maxRem = maxPx / 16;

    const slope = (maxRem - minRem) / ((maxVw / 16) - (minVw / 16));
    const intersection = -minVw / 16 * slope + minRem;

    return `clamp(${minRem}rem, ${intersection.toFixed(4)}rem + ${slope * 100}vw, ${maxRem}rem)`;
  }
});
Enter fullscreen mode Exit fullscreen mode

This math calculates the exact slope needed to scale the text smoothly between your mobile and desktop breakpoints. You would just need to update your Figma tokens to include min and max values and set a fluid flag to true. When you run this through the transform, it spits out a beautiful fluid clamp function. Your developers no longer have to write complex media queries for typography.

Step 5: The Final Configuration

Now we need to tell Style Dictionary to use our new transforms. Add this configuration to the bottom of your build.js file.

const config = {
  source: ['tokens.json'],
  platforms: {
    css: {
      transformGroup: 'css',
      transforms: ['attribute/cti', 'name/cti/kebab', 'size/pxToRem', 'size/lineHeightUnitless'],
      buildPath: 'build/css/',
      files: [{
        destination: 'variables.css',
        format: 'css/variables'
      }]
    }
  }
};

const sd = StyleDictionary.extend(config);
sd.buildAllPlatforms();
Enter fullscreen mode Exit fullscreen mode

We inject our custom size/pxToRem and size/lineHeightUnitless transforms into the pipeline. They run right before the final CSS file gets written to the disk.

The Result

Run node build.js in your terminal. Look inside the new build/css folder. You will find a variables.css file.

:root {
  --typography-heading-large-font-size: 2rem;
  --typography-heading-large-line-height: 2.5;
  --typography-heading-body-font-size: 1rem;
  --typography-heading-body-line-height: 1.5;
}
Enter fullscreen mode Exit fullscreen mode

This is exactly what we want. The 32px heading is now 2rem. The 16px body text is 1rem. If a user changes their system font size, your entire application will scale beautifully. You get the best of both worlds. Designers get to keep working in pixels inside Figma. Developers get clean relative units in the codebase.

Setting this up manually can get tedious. You have to maintain the Node scripts and handle edge cases like letter spacing or missing values. Honestly I got tired of doing this manually for every new project. I built a plugin called Design System Sync that handles all this formatting automatically. It exports your Figma variables directly to GitHub or Bitbucket via pull requests. It converts pixels to rems by default and supports W3C standard formats. You can check out the website at https://ds-sync.netlify.app?utm_source=devto&utm_medium=post&utm_campaign=bot or find it on the Figma Community at https://www.figma.com/community/plugin/1561389071519901700?utm_source=devto&utm_medium=post&utm_campaign=bot.

Top comments (0)