Optimizing H5 Pages for Foldable Screens with PostCSS, VW, and Flexible.js
This article explains how to adapt H5 product detail pages for foldable devices by comparing PostCSS‑to‑vw, CSS media queries, and a flexible.js + postcss‑px‑to‑rem workflow, then shows how to add foldable‑screen detection logic and layout tweaks to improve readability and content density.
1. Main adaptation solutions research
1.1 PostCSS + Viewport Units (vw) solution
Technical principle:
Convert the px units in the design draft to vw using the postcss-px-to-vw plugin, allowing dynamic scaling based on viewport width.
Implementation example:
// postcss.config.js
module.exports = {
plugins: {
'postcss-px-to-vw': {
viewportWidth: 375, // design width
viewportUnit: 'vw', // conversion unit
minPixelValue: 1,
mediaQuery: false // do not convert px in media queries
}
}
}Foldable‑screen adaptation example:
/* Base style */
.title {
font-size: 8.5333vw; /* 32/375 * 100 */
}
/* Limit size when unfolded */
@media (min-width: 540px) and (max-aspect-ratio: 1/1) {
.title {
font-size: clamp(16px, 4vw, 24px); /* dynamic limit */
}
}Advantages
Native CSS implementation – no JavaScript dependency, best compatibility.
True responsive behavior – scales naturally with viewport width.
Excellent performance – no runtime calculations.
Simple maintenance – clear, intuitive style code.
Disadvantages
Font control can be complex: small screens may produce tiny text, large screens may produce overly large text, requiring clamp() or similar functions.
Migration cost for legacy projects – all styles need to be rewritten.
1.2 CSS Media Query solution
Technical principle:
Use traditional CSS media queries to apply different styles for different screen sizes – the classic responsive layout method.
Implementation example:
/* Base layout */
.product-list {
display: grid;
grid-template-columns: 1fr;
gap: 12px;
}
/* Foldable‑screen expanded layout */
@media (min-width: 540px) and (max-aspect-ratio: 1/1) {
.product-list {
grid-template-columns: repeat(4, 1fr);
gap: 2vw;
}
}Advantages
Native CSS support – no JavaScript, best compatibility.
Simple and direct – a few media queries achieve layout changes.
Optimal performance – no runtime overhead.
Precise control – can target specific breakpoints.
Disadvantages
High code redundancy – many media queries increase maintenance cost.
Coarse granularity – only breakpoint‑based adjustments, lacking fine‑grained dynamic scaling.
Maintenance difficulty as breakpoints grow.
Less smooth responsive experience compared to dynamic scaling solutions.
1.3 flexible.js + postcss-px-to-rem solution
Technical principle:
Combine flexible.js with postcss-px-to-rem to convert px to rem based on viewport width, enabling dynamic font scaling.
Advantages
Automatic unit conversion – write designs in px, the plugin converts to rem.
Design‑to‑code 1:1 mapping – set rootValue: 75 for a 750 px design.
Real‑time layout adjustment – flexible.js listens to resize and recalculates root font size.
Selective conversion – selectorBlackList can exclude elements.
Manual rem override – higher priority than plugin conversion.
Build‑time conversion – no runtime cost, more efficient than pure JavaScript solutions.
2. Solution comparison analysis
Performance: postcss-px-to-vw and CSS media queries have no runtime overhead, while flexible.js adds a small JavaScript cost.
Foldable‑screen adaptation: flexible.js + postcss‑px‑to‑rem requires only one change, whereas the vw solution struggles with precise font control and media queries need manual adjustments.
Legacy migration: flexible.js can be added without rewriting existing styles; the vw approach needs a full rewrite, and media queries demand extensive refactoring.
Font precision: flexible.js offers exact control, vw needs extra constraints, media queries provide precise control at breakpoints.
3. Specific implementation and optimization
The original flexible.js limit of 540 * dpr caused oversized fonts when the screen was unfolded. Adding a width‑ratio check (0.8–1.0) treats such cases as folded and caps the calculation width at 370 px, keeping font size consistent.
// Calculate root font size
function refreshRem() {
var width = docEl.getBoundingClientRect().width;
if (width / dpr > 540) {
width = 540 * dpr;
}
// Foldable‑screen detection
var screenWidth = win.screen.width;
var screenHeight = win.screen.height;
if (screenWidth / screenHeight >= 0.8 && screenWidth / screenHeight < 1) {
width = 370;
}
var rem = width / 10;
docEl.style.fontSize = rem + 'px';
flexible.rem = win.rem = rem;
}
win.addEventListener('resize', function () {
clearTimeout(tid);
tid = setTimeout(refreshRem, 300);
}, false);After adding this logic, the unfolded view shows more content without enlarged fonts.
4. Other scenario optimization solutions
4.1 Product list layout
Use a media query to switch from a single‑column layout to a two‑column layout after unfolding, increasing product exposure.
/* Default 1‑column layout */
.product-list {
display: grid;
grid-template-columns: 1fr;
gap: 12px;
}
/* When width ≥ 540px, switch to 2 columns */
@media (min-width: 540px) {
.product-list {
grid-template-columns: repeat(2, 1fr);
}
}4.2 Image height handling
Fixed image content
.product-card img {
width: 100%;
aspect-ratio: 1/1; /* explicit ratio */
object-fit: cover;
}Non‑fixed image content
Option 1 – use the <picture> element to serve different images based on screen size.
<picture>
<!-- Load wide.jpg when unfolded -->
<source media="(min-width: 540px) and (max-aspect-ratio: 1/1)" srcset="wide.jpg">
<!-- Default square.jpg -->
<img src="square.jpg" alt="商品" class="product-img">
</picture>Option 2 – JavaScript dynamic replacement (less recommended).
function updateProductImages() {
const ratio = window.innerWidth / window.innerHeight;
const isFoldableExpanded = ratio >= 0.8 && ratio < 1;
document.querySelectorAll('.product-img').forEach(img => {
img.src = isFoldableExpanded ? 'wide.jpg' : 'square.jpg';
});
}
window.addEventListener('resize', updateProductImages);Multi‑row multi‑column layout
Apply the same grid technique to increase columns from 2 to 4 when the screen is wide.
5. Summary
By analyzing the strengths of the existing flexible.js + postcss‑px‑to‑rem workflow, we chose a progressive optimization rather than a complete rewrite. Adding foldable‑screen detection logic allowed seamless adaptation to new devices while preserving development habits and project stability.
Foldable‑screen state detection: use width‑height ratio (0.8–1.0) to identify the expanded state.
Dynamic font control: cap calculation width at 370 px in expanded mode to keep font size consistent.
Responsive layout improvements: media queries enable multi‑column grids, increasing information density.
Image content adaptation: CSS or <picture> strategies support different visuals for various screen states.
Adaptation results:
Information display efficiency increased by ~40% on unfolded foldable screens.
Font size consistency reduces reading fatigue and improves user experience.
Migration cost is near zero because the optimization builds on the existing workflow.
Overall, H5 pages require a balanced approach that considers existing front‑end tooling, business requirements, and team infrastructure. The progressive enhancement of flexible.js + postcss‑px‑to‑rem successfully brings foldable‑screen compatibility and a better user experience.
大转转FE
Regularly sharing the team's thoughts and insights on frontend development
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
