lib-flexible
可伸缩布局方案
A small JavaScript library from Alibaba's mobile team that makes mobile web pages scale correctly across different phone screen sizes by dynamically setting a root font size based on screen width and pixel density.
lib-flexible is a small JavaScript library for making mobile web pages adapt to different screen sizes, created by Alibaba'''s mobile front-end team. It addresses a common problem: a designer produces layouts in fixed pixel dimensions, but phones come in many different screen widths and pixel densities. This library bridges that gap by dynamically calculating a root font size that the rest of the page uses to scale everything proportionally.
When the script loads, it reads the device'''s screen width and pixel density (called DPR, or device pixel ratio), then sets a font-size value on the HTML element. From that point, page elements sized in rem units, a CSS measurement that is always relative to the root font size, will automatically scale to fit the screen. A designer'''s 750-pixel-wide mockup becomes a proportionally correct layout on a 375-pixel phone and on a 414-pixel one.
Font sizes are handled slightly differently from other elements. Because text does not always look good when scaled proportionally, the library provides a separate mechanism using a data-dpr attribute on the HTML element, which lets CSS target different font sizes for different screen densities explicitly.
An optional grid module is included that generates column-based CSS layouts from a specification: number of columns, column width, gutters, and page margins are passed in, and matching CSS rules come out.
The README note at the top states that if mobile adaptation feels painful, the author now recommends a newer approach using viewport-relative CSS units (vw) instead of this rem-based method, and links to an article explaining that approach. The library still works but represents an older solution to the problem.
Where it fits
- Make a mobile web page built from a fixed-pixel designer mockup display correctly on phones with different screen widths.
- Use rem CSS units so all page elements scale proportionally across different Android and iPhone screen sizes.
- Generate a grid CSS layout from column count, gutter width, and margin specs using the included optional grid module.