跪拜 Guibai
← Back to the summary

Mobile REM Adaptation: The Conversion Pipeline Behind rootValue and Dynamic Root Font Size


theme: qklhk-chocolate

Mobile REM Adaptation: Understanding rootValue, Root Font Size, and Size Conversion

"How does your project handle screen adaptation?"

While organizing this question, I found that the most confusing part is: the source code clearly says px, why does the page change with width? What is the actual relationship between rootValue and the html font size?

This note uses the common postcss-pxtorem + dynamic root font size approach in mobile H5 as an example, connecting the conversion process, implementation details, and interview follow-ups.

When converting, divide by rootValue; when displaying, multiply by root font size.

1. Two Stages: Converting CSS and Calculating Sizes

The complete process can be split into two lines:

Development server / production build: source px → postcss-pxtorem → rem in CSS

Browser runtime: layout viewport width changes → update html font size → recalculate sizes corresponding to rem
Participant When it works What it does
postcss-pxtorem When processing CSS during dev server or production build Converts eligible px to rem based on configuration
Root font size setting logic, like a custom script or amfe-flexible Browser runtime Sets the html font size according to an agreed width rule
Browser When parsing styles and related value changes Calculates sizes for rem based on the root font size, updates layout and rendering

When the window becomes wider, the plugin does not re-convert CSS. What changes is the root font size and the sizes the browser calculates from it.

This article discusses rem in the browser. rpx is an adaptation unit used by platforms like mini programs (the viewport width is usually 750rpx by default). It does not depend on the web page's html font size and should not be mixed into the same conversion flow.

2. rem's Base Is the Root Font Size

In an HTML page, 1rem corresponds to the computed font size of the root element html. For example:

html {
  font-size: 16px;
}

.title {
  font-size: 1.5rem; /* 1.5 × 16px = 24px */
}

If you change the root font size to 14px, .title's font size becomes 21px, while its declaration remains 1.5rem.

Two things need to be distinguished here:

When the root font size remains fixed, rem does not automatically scale with the viewport width. It can also be used on PC pages and does not require a whole-page proportional scaling approach.

Memory: rem depends on the root font size; whether the root font size follows the viewport is determined by the scheme.

3. How Do rootValue and Root Font Size Work Together?

3.1 Why Is It Often Set to 37.5?

Assume the project has two agreements:

  1. The px values in source code are written according to a 375-width design annotation.
  2. The root font size is calculated as current layout viewport width ÷ 10, meaning the viewport width corresponds to 10rem.

At the baseline width 375px, the root font size is:

375 ÷ 10 = 37.5px

To make the converted sizes match the design annotation at this width, the conversion baseline is set to rootValue: 37.5. For example, a card has width: 150px in source:

When converting: 150 ÷ 37.5 = 4, getting width: 4rem
When displaying: 4 × current root font size, getting the actual CSS pixel size
Layout viewport width Root font size: width ÷ 10 Card width in CSS Converted card width
375px 37.5px 4rem 150px
414px 41.4px 4rem 165.6px

rootValue is the baseline for conversion; the root font size is the basis for the browser's runtime calculation. At the baseline width, the two values are equal, but they are not the same configuration and do not automatically sync.

You can express their relationship as a formula:

Displayed size (CSS px) = source px value ÷ rootValue × current root font size (CSS px)

Under the above agreement, you can further derive:

rootValue = width scale used in design annotation ÷ 10
current root font size = current layout viewport width ÷ 10

Displayed size = source px value × current layout viewport width ÷ width scale used in design annotation

This is the reason sizes scale proportionally with the viewport width. The 10 is a project convention, not a rule of rem; if you choose a different convention, both the conversion baseline and the root font size rule must be adjusted accordingly.

3.2 Does a 750 Design Mockup Always Need rootValue Set to 75?

The key is: which annotation scale is used in the source code.

Still assuming the viewport width corresponds to 10rem, the following three approaches all make the same card display as 150px on a 375px viewport:

Annotation method in source Card width in source rootValue Conversion result
Using the 375 scale 150px 37.5 4rem
Directly using the 750 scale 300px 75 4rem
Halving 750 annotations, then using 375 scale 150px 37.5 4rem

Therefore, you cannot just look at the design image width, nor can you set rootValue to 75 just because the device pixel ratio (DPR) is 2. You need to look at the actual numeric convention written in the source code and keep the project's conventions consistent.

Memory: the design annotation determines the divisor, and the current viewport determines the root font size.

4. Putting This Scheme into Code

4.1 First, Set the Mobile Viewport

Add this to the <head> of your HTML:

<meta name="viewport" content="width=device-width, initial-scale=1.0" />

Some mobile browsers, to be compatible with desktop pages, may first use a wider layout viewport, like about 980px, and then shrink the entire page to fit the screen. This number is not fixed across all browsers.

Here, 375px and 414px refer to CSS pixels, not physical screen pixels. The viewport configuration provides a reasonable mobile viewport base, but the page still needs to implement its own layout and size adaptation.

4.2 Configuring PX-to-REM Conversion

The following uses postcss-pxtorem 6.x and PostCSS 8, and works in build tools that support loading a PostCSS config:

npm install -D postcss@8 postcss-pxtorem@6
// postcss.config.cjs
module.exports = {
  plugins: {
    "postcss-pxtorem": {
      rootValue: 37.5,    // divisor for conversion, does not set html font size
      propList: ["*"],   // allow all CSS properties to be converted
      mediaQuery: false, // keep px in media query conditions
    },
  },
};

A CommonJS config file with the .cjs extension is used here to avoid confusion with the project's ES Module settings. If you already have a PostCSS config, you can merge this plugin into it.

Source CSS:

.card {
  width: 150px;
  font-size: 15px;
}

Converted CSS:

.card {
  width: 4rem;       /* 150 ÷ 37.5 */
  font-size: 0.4rem; /* 15 ÷ 37.5 */
}

propList: ["*"] does not mean every px in the project gets converted:

4.3 Setting the Root Font Size in the Browser

The following simplified script shows only the core logic and can be executed in the browser entry:

function updateRem() {
  const width = document.documentElement.clientWidth;
  document.documentElement.style.fontSize = `${width / 10}px`;
}

// Calculate on first page load
updateRem();

// Recalculate when the window size changes
window.addEventListener("resize", updateRem);

// Recalculate when restoring a page from the browser's back-forward cache
window.addEventListener("pageshow", (event) => {
  if (event.persisted) {
    updateRem();
  }
});

When the viewport changes from 375px to 414px, the script changes the root font size from 37.5px to 41.4px. The browser recalculates .card's width and font size accordingly. The 4rem and 0.4rem in CSS are not rewritten to px strings by the script.

4.4 When Using amfe-flexible, Understand the Version

You can also use amfe-flexible instead of the custom script above, but you should choose only one of the two. Take [email protected] as an example:

npm install [email protected]
// Import in the browser entry main.js
import "amfe-flexible";

This version sets the root font size using document.documentElement.clientWidth / 10 and listens to resize and pageshow for back-forward cache recovery. It does not configure viewport for you, so you still need the <meta> tag above.

However, the library's complete behavior goes beyond this: it also sets an inline font size on body and checks for hairline support. Early flexible implementations also involved different viewport scaling and width limit logic. Do not mix behaviors from different versions. When integrating, check the actual version and its impact on existing styles.

5. Sizes Change, but Layout Isn't Necessarily Reasonable

Should Fonts Also Scale Proportionally?

With propList: ["*"], the example's font-size: 15px is also converted to 0.4rem: at a 375px viewport it becomes 15px, at 414px it becomes 16.56px.

This matches proportional conversion, but whether it is readable depends on the content. On narrow screens, fonts may be too small; on wide screens, they may be too large. So font sizes need to be evaluated separately, not just pursue the design mockup's proportions.

Also note: if you directly set the root font size to the viewport-derived px value, using rem does not mean it will automatically follow the user's browser default font size. For reading-oriented pages, you can keep the root font size linked to the user's default font, handle layout adaptation and font size separately, and verify readability after font scaling.

Why Does Overflow Still Happen with rem?

rem handles size conversion but does not arrange content. When text grows, copy lengthens, or line wrapping occurs, a fixed-height container may still not fit.

Real layout also requires Flexbox, Grid, proper wrapping, and appropriate width/height constraints. For body text, let the height be determined by content, and use unit-less values like 1.5 for line-height, which calculates based on each element's font size.

Should PC Pages Also Use Viewport Divided by 10?

rem can be used on PC, but "viewport width ÷ 10" for whole-page proportional scaling is more suitable for mobile pages with clear proportional needs. PC and cross-device pages typically also need fluid layouts, breakpoints, and maximum content widths.

If you set a maximum content width for the page, you should also consider the width used in the root font size calculation. Otherwise, after the container stops widening, the root font size continues to increase, and internal elements may overflow.

Memory: rem handles size relationships, layout handles content arrangement, and fonts need readability consideration.

6. Interview Quick Recap

First remember five keywords: viewport, divisor, root font size, conversion, layout.

viewport: determines the mobile viewport base
rootValue: the divisor used during conversion
html font-size: the basis for the browser to calculate rem when displaying
displayed size: source px value ÷ rootValue × current root font size
layout and readability: determine whether the page is actually usable after conversion

How Does Your Project Handle Mobile Adaptation?

If the project actually uses the scheme in this article, you can structure your answer like this, replacing with the design scale and tools your project actually uses:

The project writes px according to the agreed design annotation. PostCSS converts the sizes that need adaptation to rem. The browser dynamically sets the root font size based on the layout viewport width. When the width changes, it recalculates the sizes corresponding to rem. For example, with a 375 scale and agreeing that the viewport width is 10rem, configure rootValue to 37.5 and set the root font size to the current viewport width divided by 10. Layout, text wrapping, and font readability need to be handled separately.

Is rootValue the Same as html's font-size?

No. rootValue is the divisor used during CSS conversion. The html font size is what the browser uses to calculate rem. They need to work together under the same design convention, but the plugin does not set the root font size, and the browser does not read this plugin configuration.

Why Is It Sometimes 37.5 and Sometimes 75?

Under the "viewport width is 10rem" convention, if you write values directly using the 375 scale, use 37.5; if you write them using the 750 scale, use 75. If the 750 annotation is halved before writing into source, it should still be 37.5. You cannot decide based only on image width or device DPR.

When the Window Changes Size, Does PX Get Re-Converted to REM?

No. The plugin completes the conversion during the dev server or production build. When the window changes, the root font size is updated, and the browser recalculates the sizes of existing rem declarations.

Is flexible Required for Adaptation?

No. rem is a CSS unit; flexible is just one implementation for setting the root font size. You can also use custom scripts, media queries, or a vw-based root font size rule, depending on whether you need continuous scaling or breakpoint-based adjustments.

Does Using rem Guarantee the Page Won't Break?

No, it does not guarantee that. rem only establishes a relative size relationship. Issues like fixed heights, long text, and over-scaling on wide screens still need to be handled through layout, wrapping, and size constraints. Fonts also need to be verified for readability separately.

References

Comments

Top 1 from juejin.cn, machine-translated. The original thread is authoritative.

组合搭配函数

The separation of rootValue and root font size is spot on; the two 37.5 values look identical but aren't the same thing. For the 750 design draft, choosing 75 or 37.5, I used to make assumptions without thinking.