Converting em to px in JavaScript

This article can be read in about 2 minutes.
PR

The purpose 


Here’s how to convert em units to px (pixels) in JavaScript, which are commonly used in CSS:

PR

Code

Here’s a JavaScript function that converts an em size to a px size.

The second argument is the HTML element whose computed font size will be used as the base for the conversion.

function em2px(em_size, ele) {
  const parentElement = ele.parentElement || document.body;
  const px_size = parseFloat(getComputedStyle(parentElement).fontSize);
  return px_size * em_size;
}

explanation of the JavaScript code


The following line of code gets how many pixels 1 em is, based on the reference DOM element:

  const px_size = deparseFloat(getComputedStyle(parentElement).fontSize);

It then multiplies this retrieved value by the em size to get the size in px units and returns it.

return px_size * em_size;

comment

Copied title and URL