Introduction to the

Today, this article mainly explains some basic knowledge necessary for mobile TERMINAL H5 development and mobile terminal adaptation and layout scheme. If you’ve read this article or you already know the basics of mobile, you can read my article

Mobile TERMINAL H5 web development FAQ summary

Essential knowledge of mobile terminal development -Hybrid App

pixel

A pixel is a small square with a specific position and color. Pictures, electronic screens (mobile phones, computers) are made up of several small squares with specific colors and locations. Let’s say we have a computer screen 1920 by 1080, 1920 pixels horizontally and 1080 pixels vertically.

Pixel units include device pixel, logical pixel, and CSS pixel.

Device pixel, individual pixel, device pixel ratio, CSS pixel

Equipment pixel

The device pixel, also known as the physical pixel, is the smallest display unit on the screen, that is, the actual physical unit on the device, which is determined when the device is manufactured. (iphone6 750px) are generally larger than individual pixels.

Independent pixel

A standalone pixel (DP or Dip) is a virtual pixel that is a logical unit of pixels, equal to a CSS pixel without scaling. (iphone5 320px, iphone6 375px)

Device pixel ratio

Device pixel ratio DPR is the ratio of device pixels to individual pixels. For example, the iphone6 has a DPR of 2, and the iphone6 Plus has a DPR of 3.

On the Web, the browser provides us with window.devicePixelRatio to help us get the DPR. In the CSS, you can query the media min-device-pixel-ratio to obtain the DPR. In React Native, we can also use PixelRatio. Get () to get the DPR.

@media (-webkit-min-device-pixel-ratio: 2), (min-device-pixel-ratio: 2) {}
Copy the code

What is the ratio of device pixels to device-independent pixels? The general rule is that the higher the pixel density of the screen, the more device pixels are needed to display a device-independent pixel.

CSS pixel

Use px in CSS to refer to CSS pixels, such as Width: 128px. CSS pixel sizes are easy to change. When we zoom in and out of a page, the number of CSS pixels in an element does not change, only the size of each CSS pixel changes. This means that an element with width: 128px will still be 128 CSS pixels wide when scaled 200%, but each CSS pixel will be twice as wide and tall. If the original element width was 128 device independent pixels, then the element width will be 256 device independent pixels after scaling 200%.

The relationship between CSS pixels and device-independent pixels

  • The scaling ratio is CSS pixel edge length/device-independent pixel edge length;
  • At 100% zoom, one CSS pixel is equal to one device-independent pixel;
  • At 200% zoom, one CSS pixel is equal to (2 x 2) device-independent pixels;

The Retina screen

Pixel to device ratio, let’s talk about Retina display. Retina is a display standard that compresses more pixels into a single screen, resulting in higher resolution and finer display. At normal reading distance, the human eye cannot distinguish pixel particles on the screen, making the screen display more delicate and smooth. Starting with the iPhone4, Apple has introduced Retina screens for its Macs, iphones, and ipads.

There are different ways to increase resolution

  • Normal screens increase their resolution by increasing their size.
  • Retina displays increase resolution by increasing the number of pixels per unit area of the screen (increasing PPI), or pixel density, and there you have itHigh pixel density screen.

CSS pixels can be converted differently from physical pixels of the same device size

  • Normal screen: 1px equals one physical pixel.
  • Retina Screen :1px equals four physical pixels.

K and p

We often see screens in units K and P:

  • P is the number of pixels in the vertical of the screen. 1080P means 1080 pixels in the vertical and a screen with a resolution of 1920X1080 is a 1080P screen.
  • K represents how many pixels the screen has horizontally. Generally speaking, if the horizontal pixel exceeds 2048, it belongs to 2K screen, and if the horizontal pixel exceeds 4096, it belongs to 4K screen.

inches

The physical size of the screen is usually described in inches, such as 17 and 22 for computer monitors and 4.8 and 5.7 for mobile phones. Note that the dimensions are the diagonal length of the screen. 1 inch = 2.54 cm.

PPI

PPI: The number of pixels Per Inch.

PPI can be used to describe the sharpness of a screen and the quality of an image. When using PPI description images, the higher PPI is, the higher the picture quality is; when using PPI description screens, the higher PPI is, the clearer the screen is.

Calculation Method The square root of the sum of horizontal pixel points squared and vertical pixel points squared divided by screen inches (screen diagonal length).

DPI

DPI(Dot Per Inch) : the number of points Per Inch.

Usually you will see the use of DPI to describe images and screens, which should be equivalent to PPI. DPI is most commonly used to describe printers, indicating the number of points per inch that a printer can print.

Therefore, the higher the PRINTER’s DPI, the higher the precision of the printed image, which also consumes more ink spots and time.

em

Em is the size of the element’s font size. Font size inherits the parent element’s font size even if the parent element does not have a font size. If the parent element does not have a font size, the parent element is searched up the DOM tree until it reaches the root element HTML, which has a default font size of 16px.

rem

Rem is much simpler with the em foundation, rem is only related to the font size of the root HTML element, the size is fixed, 1rem is equal to the font size of the root HTML element.

ViewPort

Layout ViewPort

Layout viewport, when displaying web pages on the mobile end, because the screen size of the mobile end is relatively small, if the web page uses the screen size of the mobile end for layout, then the layout of the whole page will be displayed incorrectly. Therefore, the mobile browser provides a layout Viewport concept, which is used to display the layout of the page. The default size of the layout Viewport is 980px, which ensures that the PC web page can be displayed on the mobile browser, but it is very small. Users can enlarge the web page manually. We can through a call to the document. The documentElement. ClientWidth/clientHeight viewport size for layout. The layout viewport is understood as the width of your web page.

Visual ViewPort

Visual viewport: Visual Viewport refers to the viewport size of the area we can see on a mobile device, usually in device-independent pixels. The relationship between visual ViewPort and layout viewport is just like we look at the scenery outside the window. The visual viewport is the window, and the scenery outside is the web content in the layout viewport. We can get the visual viewport size by calling window.innerWidth/innerHeight. Visual viewports can be understood as device-independent pixel sizes.

Ideal Viewport

Ideally, since a Layout ViewPort is typically larger than a Visual ViewPort, you must drag and zoom to see the entire page. So we came up with the concept of ideal ViewPort, which allows users to view the entire page without zooming or scrollbars, and displays the same size content at different resolutions. The Ideal ViewPort is basically a layout viewport size that is equal to the width of the device. This width can be understood as device-independent pixels, so the page designed according to the Ideal ViewPort should display the same under different resolutions. We can get the ideal viewport size by calling screen.width/height, which returns device-independent pixels. Ideal viewports can be understood as layout viewports equal to visual viewports.

Use meta tags to control viewport

The default viewPort for mobile devices is a Layout ViewPort that is wider than the screen. The default width is 980px. So we usually use the meta tag to control the viewport, and we usually set width=device-width to make the layout viewport equal to the visual viewport, which is the ideal viewport.

<meta name="viewport" content="Width = device - width, initial - scale = 1.0, the maximum - scale = 1.0, user - scalable = no" />
Copy the code

The attribute of the viewport

  • Width A positive integer or device-width defines the width of the layout viewport in pixels.
  • Height Positive integer or device-height Specifies the height of the layout viewport in pixels.
  • Initial-scale0.0-10.0 defines the initial page scaling ratio.
  • Minimum-scale0.0-10.0 defines the minimum value for scaling; The value must be less than or equal to maximum-scale.
  • Maximum-scale0.0-10.0 defines the maximum scale; Must be greater than or equal to the value of minimum-scale.
  • If set to no, users will not be able to zoom in or out of web pages. The default value is yes

Adaptation scheme

There are a variety of mobile phones and mobile screens, so it is necessary to understand adaptation schemes for mobile H5 development. That means we have a code that works with all types of phones. The schemes of mobile terminal adaptation mainly include @Media media query scheme, REM scheme and VW VH scheme. We will introduce them one by one below.

Use the CSS media query @media

Through the media query to adapt to different screens, here is not specifically introduced media query interested in learning.

@media *mediatype* and|not|only *(media feature)*  {
    CSS-Code;
}
Copy the code
@media screen and (min-width: 375px) { .box { width : 160px; }}@media screen and (min-width: 750px) { .box { width : 320px; }}Copy the code

Although media query can solve the adaptation problem, the disadvantages of using media query are also obvious

  1. All the elements on the page have to be defined in different @media with different sizes, so there’s a lot of code redundancy.
  2. If you had one more screen size, you’d have to write another @media query block.
  3. Media query block writing order is also very exquisite, behind will cover the front, it is easy to make mistakes.

The use of rem

Rem is the size of the HTML element font-size. So the core of using REM layout is dynamically setting the font size of the root HTML element. Among rem adaptation schemes, lib-flexible and AMFE-flexible schemes of Amoy system are popular.

Lib-flexible and AMFE-Flexible, two mobile terminal adaptation schemes, are implemented based on REM. The viewPort unit is compatible with many browsers, so lib-flexible and Amfe-flexible can be abandoned. Both the current version and the previous version have some problems. It is recommended that you start using viewPort instead.

lib-flexible

If you’re interested, check out the lib-Flexible source code, which automatically generates viewport meta tags.

Core code:

// The font size of the root element is the layout viewport size /10.
function refreshRem(){
  var width = docEl.getBoundingClientRect().width;
  if (width / dpr > 540) {
      width = 540 * dpr;
  }
  var rem = width / 10;
  docEl.style.fontSize = rem + 'px';
  flexible.rem = win.rem = rem;
}
Copy the code
// Dynamically generate viewPort meta tags
if(! metaEl) { 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);
  } else {
      var wrap = doc.createElement('div'); wrap.appendChild(metaEl); doc.write(wrap.innerHTML); }}Copy the code

Note:

// If it is an iPhone, it will be scaled according to DPR, the rest will not be scaled
// I think the design here is mainly to solve the 1px problem, which has been abandoned in amFE-flexible solution
if(! dpr && ! scale) {var isAndroid = win.navigator.appVersion.match(/android/gi);
  var isIPhone = win.navigator.appVersion.match(/iphone/gi);
  var devicePixelRatio = win.devicePixelRatio;
  if (isIPhone) {
      // On iOS, use 2x for 2 and 3 screens, and 1x for the rest
      if (devicePixelRatio >= 3&& (! dpr || dpr >=3)) {                
          dpr = 3;
      } else if (devicePixelRatio >= 2&& (! dpr || dpr >=2)){
          dpr = 2;
      } else {
          dpr = 1; }}else {
      // For other devices, use the same 1 times scheme
      dpr = 1;
  }
  scale = 1 / dpr;
}
Copy the code

Use of lib-flexible:

/ / installation
npm install lib-flexible --save-dev

/ / reference
import 'lib-flexible/flexible.js'
Copy the code

This will automatically generate the ViewPort meta tag for our index.html page,

With the Lib-Flexible configuration, it can be adapted to different phone screens. We just need to remember the formula: CSS size of an element = design size of an element /(design width /10). For example, if the designer’s design is 375, and if the height of an element on the design is 75px, we need to set the height of the element to 75/(375/10) = 2REM in the code.

If manual calculations are too tiring, we can use the PostCSS-Pxtorem plugin to do the calculations for us automatically.

The core of the postCSS-Pxtorem plugin is that we need to set rootValue to 37.5 if our design is 375 and 75 if our design is 750. This way we only need to set the px size of the CSS elements according to the design, and the plugin will automatically calculate the REM value for us when packaging. Isn’t that great?

// This is the default configuration of the postCSs-pxtorem plugin
{
  rootValue: 16.unitPrecision: 5.propList: ['font'.'font-size'.'line-height'.'letter-spacing'].selectorBlackList: [].replace: true.mediaQuery: false.minPixelValue: 0.exclude: /node_modules/i
}

// Usually we just need to change rootValue
{
  rootValue: 37.5,}Copy the code

amfe-flexible

Interested can have a look at amFE-Flexible source code. This version of the code is much cleaner and does not automatically generate viewPort meta tags.

Core code:

// set 1rem = viewWidth / 10
function setRemUnit () {
  var rem = docEl.clientWidth / 10
  docEl.style.fontSize = rem + 'px'
}
Copy the code

Usage:

/ / installation
npm install amfe-flexible --save-dev

/ / reference
import 'amfe-flexible/index.js'

// Add the viewPort meta tag to the index.html page
<meta name="viewport" content="Width = device - width, initial - scale = 1.0, the maximum - scale = 1.0, the minimum - scale = 1.0, user - scalable = no">
Copy the code

In amFE-Flexible, there is no DPR, no auto-generated viewport meta tags, and no page scaling, which is much simpler.

Similar to lib-Flexible, amFE-Flexible is configurable so it can be adapted to different phone screens. We just need to remember the formula: CSS size of an element = design size of an element /(design width /10). For example, if the designer’s design is 375, and if the height of an element on the design is 75px, we need to set the height of the element to 75/(375/10) = 2REM in the code.

If manual calculations are too tiring, we can use the PostCSS-Pxtorem plugin to do the calculations for us automatically.

The core of the postCSS-Pxtorem plugin is that we need to set rootValue to 37.5 if our design is 375 and 75 if our design is 750. This way we only need to set the px size of the CSS elements according to the design, and the plugin will automatically calculate the REM value for us when packaging, isn’t it great?

// This is the default configuration of the postCSs-pxtorem plugin
{
  rootValue: 16.unitPrecision: 5.propList: ['font'.'font-size'.'line-height'.'letter-spacing'].selectorBlackList: [].replace: true.mediaQuery: false.minPixelValue: 0.exclude: /node_modules/i
}

// Usually we just need to change rootValue
{
  rootValue: 37.5,}Copy the code

The use of vw vh

  • Vw: short for viewport’s width, screen width = 100VW.
  • Vh: similar to vw, short for viewport’s height = 100V.
  • Vmin: The value of vmin is the smaller value of the current VW and VH.
  • Vmax: The value of vmax is the current larger value of VW and VH.

Vw and VH adaptation is easier than REM adaptation, we just need to set the viewport meta tag and then use it directly.

Usage:

// Add the viewPort meta tag to the index.html page
<meta name="viewport" content="Width = device - width, initial - scale = 1.0, the maximum - scale = 1.0, the minimum - scale = 1.0, user - scalable = no" />
Copy the code

Lib-flexible and AmFE-Flexible are used in a similar way as above, so they can be adapted to different phone screens. We just need to remember the formula: CSS size of an element = design size of an element /(design width /100) vw. For example, if the designer’s design is 375, let’s say the height of an element on the design is 75px, we need to set the height of the element in the code to 75/(375/100) = 20vw. The thing to notice here is that we can only use vw for width and height.

If manual calculations are too tiring, we can use the postCSs-px-to-viewport plugin to do the calculations for us automatically.

The core of the postCSs-px-to-viewPort plugin is that we need to set the width of the viewportWidth (the width of the postCSs-pxtorem). If our design is 375, we need to set the viewportWidth to 375. If our design is 750 we just set the viewport to 750. In this way, we only need to set the px size for the elements in the CSS according to the design draft, and the plug-in will automatically calculate the vw value for us when packaging, isn’t it great?

// This is the default configuration of postcss-px-to-viewPort
{
  unitToConvert: 'px'.viewportWidth: 320.unitPrecision: 5.propList: [The '*'].viewportUnit: 'vw'.fontViewportUnit: 'vw'.selectorBlackList: [].minPixelValue: 1.mediaQuery: false.replace: true.exclude: undefined.include: undefined.landscape: false.landscapeUnit: 'vw'.landscapeWidth: 568
}
// Generally we just need to change the viewportWidth
{
  viewportWidth: 375,}Copy the code

The Ignoring feature of the postCSS-px-to-viewPort plugin can also be used to annotate properties that do not require conversion

  • /* px-to-viewport-ignore */ The current line is not converted
  • /* px-to-viewport-ignore-next */ The next line is not converted
.box {
  /* px-to-viewport-ignore-next */
  width: 10px;
  height: 10px;
  padding: 10px; /* px-to-viewport-ignore */
}
Copy the code

The layout scheme

After that, we will talk about the layout of the mobile terminal. There are many layout schemes of the mobile terminal. I recommend you to look at the mobile terminal layout tutorial in this article.

Of all the layouts, I feel we must master the Flex layout and grid layout, because these two layouts are basically indispensable in everyday H5 development. There are many tutorials on Flex layout and Grid layout, but I don’t want to teach you how to use grid layout. I recommend you to read Ruan yifeng’s Flex layout tutorial and Grid Layout tutorial. With these two sets of minds in hand, I don’t think there’s anything that will surprise you in terms of mobile H5 development layout.

extension

Common APIS for window sizes

Screen. width Specifies the screen width independent of the browser. Screen. height Specifies the screen height independent of the browser. OuterWidth Retrieves the width of the browser. This includes all borders of the browser, including sidebars, window borders, and resized Windows. OuterHeight Retrieves the height of the browser, including all of the browser's borders, including sidebars, window borders, and window resizing. Window. innerWidth: Gets the width of the browser's visual viewport, including the scroll bar. Window. innerHeight: Gets the height of the browser viewport (including the scroll bar). Document. The documentElement. ClientWidth: get the browser viewport width layout. Scroll bars are not included. Document. The documentElement. ClientHeight: access to the browser layout viewport height. Scroll bars are not included. Dom. clientHeight: Gets the height of the element including the content and the inner margin. Dom. offsetWidth: Gets the width of the element including the content, the inner margin, the scroll bar, and the border. Dom.offsetheight: Gets the height of an element, including the content, inner margin, scroll bar, and border. Dom.scrollwidth: Gets the actual width of the element's content, including the inner margin. Dom.scrollheight: Gets the actual height of the element's content, including the inner margin. Dom. offsetTop: Gets the height of the element from the top of the page. Dom. offsetLeft: Gets the width of the element from the left of the page. Dom. scrollLeft: Gets how far the element scroll bar scrolls horizontallyCopy the code

Refer to the article

Here’s what you need to know about mobile adaptation

Mobile Adaptation Solution Guide 2022 – The latest and most complete network

Afterword.

This article is the author’s personal study notes, if there are fallacies, please inform, thank you! If this article helped you, please give it a thumbs up