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.