Home Web Front-end JS Tutorial Mobile page development adaptation rem layout principle

Mobile page development adaptation rem layout principle

Nov 21, 2016 pm 05:41 PM

Principle of adapting rem layout for mobile page development

What is adaptation and why it is necessary to adapt?

The design drawings we get are generally designed based on 640, 750, 1080 resolutions, and now mobile terminals have various There are various styles, different resolutions, different logical pixels, and different viewports. So in order for our pages to be displayed well on every device, we need to do unified processing for these devices. This process is called mobile end adaptation.

Some concepts you need to know:

Physical pixel (physical pixel)

A physical pixel is the smallest physical display unit on the display (mobile phone screen), which can be understood as the resolution we usually talk about.

Device-independent pixel (density-independent pixel)

Device-independent pixel (also called density-independent pixel) can be thought of as a point in the computer coordinate system. This point represents a virtual pixel that can be used by the program (for example: css pixels), and then converted into physical pixels by the relevant system, which can be understood as the size of the visual viewport we are talking about;

So, there is a certain correspondence between physical pixels and device independent pixels, this is what happens next Let’s talk about the device pixel ratio.

Device pixel ratio (device pixel ratio)

Device pixel ratio (dpr for short) defines the correspondence between physical pixels and device independent pixels. Its value can be obtained according to the following formula: device pixel ratio = physical pixel / device Independent pixel // In a certain direction, the x direction or y direction

The device pixel ratio is also set when the device is produced. In JavaScript, the dpr of the current device can be obtained through window.devicePixelRatio.

Viewport

PC viewport refers to the content area within the browser window, excluding toolbars and scroll bars.

Viewports in mobile browsers are divided into several situations:

is called the layout viewport. The maximum value is specified by the browser manufacturer and can be documented .documentElement.clientWidth gets its width.

The browser window we see, the size of the web page area, is called the visual viewport, which is represented by css pixels (device logical pixels)

rem

rem is a part of css3 The length unit is relative to the document and element html; for example, set html font-size=100px; then 1rem=100px; all subsequent elements can use this baseline value to set the size;

Commonly used solutions:

Fixed height, width from Adapt (percentage, em)

Use rem layout

The following is a summary of NetEase's plan to use rem on Taobao's homepage

NetEase's approach:

1) Set the layout adaptability to the visual viewport without scaling, that is, the ideal viewport .

<meta name="viewport"content="initial-scale=1,maximum-scale=1, minimum-scale=1”>
Copy after login

2) Based on the resolution of the design draft and taking 100px as the reference for font-size, then if the width of the design draft is 640, the width of the body element can be set to width: 6.4rem (640/100). When When we set the layout viewport to 320, the html font-size=deviceWidth / 6.4.

3) Get deviceWidth through document.documentElement.clientWidth;

4) Set html font-size after the dom of the page is ready,

document.documentElement.style.fontSize =document.documentElement.clientWidth / 6.4 + ‘px’
Copy after login

5) Set the font size through mediaQuery. Rem cannot be used for font size because of errors Too big.

Taking the design draft of 640 as an example, the final setting html font-size code is as follows. When laying out, divide the size marked in the design draft by 100, which is the value of rem. It is quite simple

var deviceWidth = document.documentElement.clientWidth;
if(deviceWidth > 640) deviceWidth = 640;
document.documentElement.style.fontSize = deviceWidth / 6.4 + &#39;px&#39;;
Copy after login

Here if (deviceWidth > 640) deviceWidth = 640; is because when deviceWidth is greater than 640, the physical resolution is already greater than 1280 (depending on dpr), you should visit the pc website;

淘宝的做法:

原理

1) 通过dpr设置缩放比,实现布局视口大小,

var scale = 1 / devicePixelRatio;  
 document.querySelector(&#39;meta[name="viewport"]&#39;).setAttribute(&#39;content&#39;,&#39;initial-scale=&#39;+ scale + &#39;, maximum-scale=&#39; + scale + &#39;, minimum-scale=&#39; + scale + &#39;, user-scalable=no&#39;);
Copy after login

2) 动态计算html的font-size

document.documentElement.style.fontSize = document.documentElement.clientWidth / 10 + ‘px’;
Copy after login

这里的意思是,clientWidth / 10 得到是布局视口下的rem基准值(以iphone6为例 1rem=75px),那么设计稿正好也是 750,所以对应的关系 clientWidth / 10==设计稿的尺寸/x, 那么x=设计稿的尺寸/rem基准值。如果是iphone6 plus rem基准值等于clientWidth / 10 等于124.2,那么x=750/124.2。

关于具体的实现 淘宝提供了一个开源的方案lib-flexible:https://github.com/amfe/lib-flexible

具体逻辑 :

1)判断head中是否设置了viewport,如果有设置,按照已有viewport 设置缩放比;

if (metaEl) {
        console.warn(&#39;将根据已有的meta标签来设置缩放比例&#39;);
        var match = metaEl.getAttribute(&#39;content&#39;).match(/initial\-scale=([\d\.]+)/);
        if (match) {
            scale = parseFloat(match[1]);
            dpr = parseInt(1 / scale);
        }
    }
Copy after login

2)如果没有设置meta viewport,判断是否设置dpr,如果有,通过dpr计算缩放scale。

        var content = flexibleEl.getAttribute(&#39;content&#39;);
        if (content) {
            var initialDpr = content.match(/initial\-dpr=([\d\.]+)/);
            var maximumDpr = content.match(/maximum\-dpr=([\d\.]+)/);//maximum 设置最大值,与initial的值比较,取最小值;
            if (initialDpr) {
                dpr = parseFloat(initialDpr[1]);
                scale = parseFloat((1 / dpr).toFixed(2));    
            }
            if (maximumDpr) {
                dpr = parseFloat(maximumDpr[1]);
                scale = parseFloat((1 / dpr).toFixed(2));    
            }
        }
Copy after login

3)如果 dpr &scale都没有设置,那么就通过设备的dpr设置起缩放 scale,

if (!dpr && !scale) {//meta[name="viewport"]&&meta[name="flexible"]都不存在。
    var isAndroid = win.navigator.appVersion.match(/android/gi);
    var isIPhone = win.navigator.appVersion.match(/iphone/gi);
    var devicePixelRatio = win.devicePixelRatio;
    if (isIPhone) {
        // iOS下,对于2和3的屏,用2倍的方案,其余的用1倍方案
        if (devicePixelRatio >= 3 && (!dpr || dpr >= 3)) {                
            dpr = 3;
        } else if (devicePixelRatio >= 2 && (!dpr || dpr >= 2)){
            dpr = 2;
        } else {
            dpr = 1;
        }
    } else {
        // 其他设备下,仍旧使用1倍的方案
        dpr = 1;
    }
    scale = 1 / dpr;
}
Copy after login

4)得到scale之后 ,如果meta 的viewport不存在,那么就创建一meta[name=“viewport”],将scale配置进去。

    metaEl = doc.createElement(&#39;meta&#39;);
    metaEl.setAttribute(&#39;name&#39;, &#39;viewport&#39;);
    metaEl.setAttribute(&#39;content&#39;, &#39;initial-scale=&#39; + scale + &#39;, maximum-scale=&#39; + scale + &#39;, minimum-scale=&#39; + scale + &#39;, user-scalable=no&#39;);

    if (docEl.firstElementChild) {

        docEl.firstElementChild.appendChild(metaEl);
         
    }
Copy after login

5)动态改写html的font-size

    var width = docEl.getBoundingClientRect().width;//获取html的宽度
    if (width / dpr > 540) {//判断屏幕逻辑像素大于540时,取540
        width = 540 * dpr;
    }
    var rem = width / 10;
    docEl.style.fontSize = rem + &#39;px&#39;;
    flexible.rem = win.rem = rem;
Copy after login

总结:

使用rem布局,实质都是通过动态改写html的font-size基准值,来实现不同设备下的良好统一适配;

网易与淘宝不同 的地方是 ,网易将布局视口设置成了 视觉视口,淘宝将布局视口设置成了物理像素大小,通过 scale缩放嵌入了 视觉视口中;

容器元素的字体大小都不使用rem,需要额外的media查询;


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1253
29
C# Tutorial
1227
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

How do I install JavaScript? How do I install JavaScript? Apr 05, 2025 am 12:16 AM

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

See all articles