Mobile page development adaptation rem layout principle
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:
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”>
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’
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 + 'px';
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('meta[name="viewport"]').setAttribute('content','initial-scale='+ scale + ', maximum-scale=' + scale + ', minimum-scale=' + scale + ', user-scalable=no');
2) 动态计算html的font-size
document.documentElement.style.fontSize = document.documentElement.clientWidth / 10 + ‘px’;
这里的意思是,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('将根据已有的meta标签来设置缩放比例'); var match = metaEl.getAttribute('content').match(/initial\-scale=([\d\.]+)/); if (match) { scale = parseFloat(match[1]); dpr = parseInt(1 / scale); } }
2)如果没有设置meta viewport,判断是否设置dpr,如果有,通过dpr计算缩放scale。
var content = flexibleEl.getAttribute('content'); 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)); } }
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; }
4)得到scale之后 ,如果meta 的viewport不存在,那么就创建一meta[name=“viewport”],将scale配置进去。
metaEl = doc.createElement('meta'); metaEl.setAttribute('name', 'viewport'); metaEl.setAttribute('content', 'initial-scale=' + scale + ', maximum-scale=' + scale + ', minimum-scale=' + scale + ', user-scalable=no'); if (docEl.firstElementChild) { docEl.firstElementChild.appendChild(metaEl); }
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 + 'px'; flexible.rem = win.rem = rem;
总结:
使用rem布局,实质都是通过动态改写html的font-size基准值,来实现不同设备下的良好统一适配;
网易与淘宝不同 的地方是 ,网易将布局视口设置成了 视觉视口,淘宝将布局视口设置成了物理像素大小,通过 scale缩放嵌入了 视觉视口中;
容器元素的字体大小都不使用rem,需要额外的media查询;

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

Bring matrix movie effects to your page! This is a cool jQuery plugin based on the famous movie "The Matrix". The plugin simulates the classic green character effects in the movie, and just select a picture and the plugin will convert it into a matrix-style picture filled with numeric characters. Come and try it, it's very interesting! How it works The plugin loads the image onto the canvas and reads the pixel and color values: data = ctx.getImageData(x, y, settings.grainSize, settings.grainSize).data The plugin cleverly reads the rectangular area of the picture and uses jQuery to calculate the average color of each area. Then, use

This article will guide you to create a simple picture carousel using the jQuery library. We will use the bxSlider library, which is built on jQuery and provides many configuration options to set up the carousel. Nowadays, picture carousel has become a must-have feature on the website - one picture is better than a thousand words! After deciding to use the picture carousel, the next question is how to create it. First, you need to collect high-quality, high-resolution pictures. Next, you need to create a picture carousel using HTML and some JavaScript code. There are many libraries on the web that can help you create carousels in different ways. We will use the open source bxSlider library. The bxSlider library supports responsive design, so the carousel built with this library can be adapted to any

Data sets are extremely essential in building API models and various business processes. This is why importing and exporting CSV is an often-needed functionality.In this tutorial, you will learn how to download and import a CSV file within an Angular
