Feb 8, '25 02:00

How to convert PX to REM and vice versa?

In web development, relative units of measurement such as REM are often used instead of absolute PX. This helps to make the layout responsive and user-friendly. Previously, we made a more detailed post about how px differs from rem. Now, let's look at an ex...

Read post
Share
🔥 More posts
This content has been automatically translated from Ukrainian.

In web development, relative units of measurement such as REM are often used instead of absolute PX. This helps to make the layout responsive and user-friendly. Previously, we made a more detailed post about how px differs from rem. Now, let's look at an example of converting these units of measurement.

PX vs REM

  • PX (pixels) — an absolute unit of measurement that does not change depending on browser settings.
  • REM (Root EM) — a relative unit that depends on the font size of the root element (html). By default, in most browsers, 1rem = 16px.

How to convert PX to REM

To convert PX to REM, you need to divide the value in PX by the base font size (16px, if not changed).

Formula

REM = PX / 16

Example code in JavaScript

function pxToRem(px, base = 16) {
  return px / base + "rem";
}

console.log(pxToRem(32)); // "2rem"
console.log(pxToRem(20, 20)); // "1rem" (if the base size is 20px)

How to convert REM to PX

To convert REM to PX, you need to multiply the value of REM by the base font size.

Formula

PX = REM × 16

Example code in JavaScript

function remToPx(rem, base = 16) {
  return rem * base + "px";
}

console.log(remToPx(2)); // "32px"
console.log(remToPx(1.5, 18)); // "27px" (if the base size is 18px)

Using REM instead of PX helps to make the website more responsive and accessible. The conversion between these units is quite simple and can be easily implemented using formulas or a small JavaScript script.

🔥 More posts

All posts
Feb 7, '25 02:00

What is HTML?

HTML (HyperText Markup Language) – is a markup language used to create web pages. It defines the struc...

Feb 7, '25 02:00

How to convert HWB to RGB?

Colors in HWB format are not often used in web design and programming. But sometimes it's necessary to...

Feb 7, '25 02:00

How to convert RGB to HWB?

If you need to convert RGB to HWB, you can use a formula that allows you to obtain hue (H), whiteness ...

Feb 8, '25 02:00

How to convert CMYK to RGB?

CMYK and RGB are two different color models used for printing and digital displays, respectively. If y...

Feb 8, '25 02:00

How to convert RGB to CMYK?

RGB and CMYK are two main color models used for digital displays and printing, respectively. If you ar...