Convert em to px using JavaScript

この記事は約2分で読めます。
スポンサーリンク

Things I want to do

This converts the `em` unit, used in CSS and other applications, to `px` units.

スポンサーリンク

code

The following function will return the size in pixels when you pass it the size in em.

The second argument is the element that displays the object to be transformed.

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

Code explanation

The following line retrieves how many pixels 1em represents from the base DOM element.

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

The obtained value is multiplied by the size in em units to get the size in pixels, which is then returned.

return px_size * em_size;

コメント

タイトルとURLをコピーしました