DEV Community

Dev Nestio
Dev Nestio

Posted on

Build a CSS Unit Converter: px, rem, em, vw, vh and More

CSS unit conversion is a constant daily task. I built a browser-only converter supporting 10 unit types.

Try it: https://devnestio.pages.dev/px-rem-converter/

Units supported

px, rem, em, vw, vh, pt, pc, cm, mm, in

Core conversion

function toPx(value, unit) {
  const base = getBase(), parent = getParent(), vpW = getVpW(), vpH = getVpH();
  switch(unit) {
    case 'px':  return value;
    case 'rem': return value * base;
    case 'em':  return value * parent;
    case 'vw':  return value * vpW / 100;
    case 'vh':  return value * vpH / 100;
    case 'pt':  return value / 0.75;
    case 'pc':  return value * 16;
    case 'cm':  return value / 0.026458;
    case 'mm':  return value / 0.26458;
    case 'in':  return value / 0.010417;
  }
}

function convertFrom(srcUnit) {
  const px = toPx(parseFloat(document.getElementById('inp-'+srcUnit).value), srcUnit);
  UNITS.forEach(u => {
    if (u.id !== srcUnit)
      document.getElementById('inp-'+u.id).value = fmt(fromPx(px, u.id));
  });
}
Enter fullscreen mode Exit fullscreen mode

Features

  • Configurable base font, parent font, viewport width/height
  • Live conversion across all 10 units simultaneously
  • Common px → rem reference table
  • Conversion formula cheat sheet

DevNestio — browser-only developer tools.

Top comments (0)