Skip to content
Created: April 6, 2021

H5 (mobile terminal) adaptation solution summary - including ideas, advantages and disadvantages, common implementations (code snippets), tool/build chain suggestions, and final implementation checklist.Depending on the project style and team preference, you can choose one main solution (I recommend dynamic rem + postcss automatic conversion + responsive images + a few media queries), and use the others as supplementary means.

1) Common adaptation ideas (quick overview of advantages and disadvantages) ​

  • Fixed pixels (px) + multiple sets of UI Advantages: Simple to implement and controllable.Disadvantages: high maintenance cost, poor experience (not suitable for various screens).
  • Media queries Advantages: precise control of different breakpoints.Disadvantages: When there are many breakpoints, the style is complex and maintenance is difficult.
  • Percent/Flexible Layout (flex/grid + %) Advantages: Natural responsiveness, good adaptability to width changes.Cons: Some size/font controls aren't fine enough.
  • Dynamic rem (set root font size according to screen width) - Recommended mainstream approach Advantages: Proportionally scalable, good development experience, combined with PostCSS, can be written in px, automatically changed to rem.Disadvantages: JS initialization needs to be run, and DPR/maximum and minimum restrictions need to be considered.
  • viewport unit (vw/vh/clamp) Advantages: Achieve minimalist scaling, suitable for elements scaling proportionally with the screen.Disadvantages: 100vh behaves strangely on mobile keyboards/browser toolbars (needs to be fixed).
  • Mixed (rem + media queries + flex/grid + responsive images) - the safest

2) Recommended: dynamic rem + PostCSS pxtorem + responsive image (detailed implementation) ​

2.1 HTML basic meta ​

html
<!-- 基础 -->
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">

<!-- iPhone X 刘海 / 安全区 -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">

If you need to handle the iOS safe area (notch), use CSS env() or constant():

css
body {
  padding-top: env(safe-area-inset-top);
  padding-left: env(safe-area-inset-left);
  padding-right: env(safe-area-inset-right);
  padding-bottom: env(safe-area-inset-bottom);
}

2.2 Dynamic rem (common implementation: according to the design draft width 375 or 750) ​

Set the root element font-size to windowWidth / designWidth * base (base is usually 100 or 16).Example JS (placed in <head> for early execution):

html
<script>
(function() {
  const designWidth = 375; // 设计稿宽度(可选 750 按 2x)
  const base = 10;         // 例如:1rem = 10px(可按喜好)
  function setRem() {
    const docEl = document.documentElement;
    const width = docEl.clientWidth || window.innerWidth;
    const maxWidth = 768; // 限制最大宽度,防止桌面太宽
    const usedWidth = Math.min(width, maxWidth);
    docEl.style.fontSize = (usedWidth / designWidth) * base * 10 + 'px';
    // 如果 base=10,上面的乘 10 可调整成直接 (usedWidth/designWidth)*100 => 1rem=100px 情况
  }
  setRem();
  window.addEventListener('resize', setRem);
  window.addEventListener('orientationchange', setRem);
})();
</script>

A more common approach: 1rem = (clientWidth / designWidth) * 100px, which is more intuitive to write px to rem.You can make an appointment as a team.

CSS usage examples

css
/* 假设 1rem = 100px (设计宽 375 -> root 37.5px => 1rem ≈ 37.5px) */
.header { height: 1.0rem; }    /* 约等于设计稿中的 100px */
.btn { padding: .24rem .4rem; font-size:.14rem; }

2.3 PostCSS automatically converts px to rem (dev-friendly) ​

Install and configure postcss-pxtorem so that engineers still write in px and automatically convert to rem when building. Example postcss.config.js:

js
module.exports = {
  plugins: {
    'postcss-pxtorem': {
      rootValue: 37.5, // 对应 1rem 等于多少 px(与上面 JS 的 root 对齐)
      propList: ['*'],
      unitPrecision: 5,
      minPixelValue: 1,
    },
    // 其他插件...
  }
}

Note: rootValue must be aligned with the root font-size set by your script (or mobile/desktop by build phase).

2.4 Images and Media Resources (Responsive) ​

  • Use srcset / <picture>: Provide 1x / 2x / 3x (adapted to high DPR devices).
html
<img src="small.jpg"
     srcset="image@1x.jpg 1x, image@2x.jpg 2x, image@3x.jpg 3x"
     alt="...">
  • Use sizes + srcset to reduce traffic.
  • WebP takes precedence and falls back to JPEG/PNG.

2.5 Font size and clamp() (taking into account readability) ​

To prevent fonts from being too small/large on very small or very large screens, use CSS clamp():

css
html { font-size: 16px; }
h1 { font-size: clamp(1.2rem, 2.4vw, 2rem); }

2.6 Dealing with 100vh problem (mobile address bar) ​

The mobile terminal 100vh will be affected by the address bar. It is recommended to use JS variables:

js
function setVh() {
  document.documentElement.style.setProperty('--vh', window.innerHeight * 0.01 + 'px');
}
setVh();
window.addEventListener('resize', setVh);

Then in CSS:

css
.fullscreen { height: calc(var(--vh) * 100); }

2.7 DPR / physical pixel considerations (when necessary) ​

If you need to adapt images or icons according to DPR, you can read window.devicePixelRatio or generate multiple image resources on the server side.

3) Supplement: Common components and strategies ​

  • Touch target: Button/clickable element is recommended to be at least 44–48px (can be represented by rem).
  • Tap Feedback: Go to -webkit-tap-highlight-color: transparent; and provide visible tap state.
  • Form Control: Mobile input (input) font should not be lower than 16px to prevent iOS from enlarging (or setting meta).
  • Prevent iOS from automatically recognizing phone numbers:
html
<meta name="format-detection" content="telephone=no">
  • Viewport scaling policy: maximum-scale=1,user-scalable=no has accessibility issues, use with caution.If the project has accessibility requirements, scaling is allowed.
  • Offline/caching strategy: Properly use service workers to cache static resources and optimize the speed of the first screen.
  • Above the Fold Performance: Critical CSS, lazy loading of images, and asynchronous loading of non-critical JS.

vw/vh is The most modern layout method for mobile terminals :

  • ✔ No rem script required
  • ✔ Naturally responsive
  • ✔ Excellent visual effects
  • ✔ Best used with PostCSS

But:

  • ❗ font-size is not suitable for vw
  • ❗ 100vh unreliable
  • ❗ Business UI is not suitable for 100% scaling
Scene typeIs it suitable for vw/vh
Marketing page, event page, landing page⭐⭐⭐⭐⭐ Highly recommended
Animation, visual draft, brand display page⭐⭐⭐⭐⭐
Mini Program WebView⭐⭐⭐⭐
Information display website⭐⭐⭐
Business backend/form/e-commerce/order management⭐⭐ (mixed use is better)

4) Build chain and tool suggestions ​

  • Use PostCSS + postcss-pxtorem to automatically convert px → rem.
  • For RN web/framework projects, consider designing tokens (JSON) to be exported to the component library.
  • Use Lighthouse/WebPageTest for mobile performance testing.
  • Use Chrome Device Mode/Real Device Test/BrowserStack to verify compatibility.
  • Image processing: Use sharp to generate multiple resolution images during the build phase.

5) Sample directory structure and practical steps (implementation guide) ​

  1. Project agreement: Design draft width designWidth = 375, 1rem=100px calculation method (unified by the team).
  2. Insert dynamic rem script in index.html <head> (execute as early as possible).
  3. Configure PostCSS's postcss-pxtorem to automatically convert it during build.
  4. When writing components, give priority to using rem (or continue to write px and convert it to pxtorem), and use Flex/Grid layout.
  5. Images use srcset and generate multi-resolution resources at build time.
  6. Add --vh JS to solve 100vh problem.
  7. Testing: Test key pages (login, homepage, forms) on iOS, Android, multiple devices, and horizontal and vertical screens.
  8. Performance optimization and accessibility checks.

6) Common pitfalls and precautions ​

  • Inconsistency between root font-size and postcss rootValue will cause conversion misalignment.
  • The iOS input box evokes the soft keyboard to push up the page, and the layout is unbalanced - pay attention to monitoring focus/blur and perform scrolling/fixed element processing.
  • Disabling zoom affects accessible users; if accessibility requires it, allow zoom and consider large print mode in your design.
  • dp vs px concept: design draft px ≠ device physical pixels, pay attention to DPR.

7) Quick decision matrix (helps you choose a plan) ​

  • The project is short-term, has many content pages, and the team wants to work quickly: flex + % + media queries (simple and fast).
  • The project is long-term, componentized, and needs to be unified: dynamic rem + postcss-pxtorem + responsive image (recommended).
  • Emphasis on pixel-level restoration (strictly for games/graphics): use multiple sets of resources or canvas customization.

8) Implementation checklist (before going online) ​

  • Root font-size aligned with pxtorem rootValue
  • iOS safe area (safe-area-inset) is handled correctly
  • Image provided 1x/2x/3x or use srcset
  • 100vh processing (use --vh)
  • Forms scroll/focus correctly when invoked by soft keyboard
  • Touch target ≥ 44–48px
  • Lighthouse mobile performance score passes key thresholds
  • Accessibility Zoom Test (can zoom up to 200%)
  • Real device testing (at least covering iOS Safari, Chrome Android)