## Introduction

Mobile adaptation is something we often encounter in development, which may encounter many problems:

• `1px`Problem
• `UI`Figure perfect adaptation scheme
• `iPhoneX`Adaptation plan
• Blurring of High Definition Screen Pictures

The above problems may be that we already know how to solve them in the development, but the principle of the problem and the principle of the solution may be ambiguous. In the process of solving these problems, we often encounter many concepts: pixel, resolution,`PPI``DPI``DP``DIP``DPR`, viewports, etc., can you really distinguish the meaning of these concepts?

Starting from the basic concept of mobile terminal adaptation, this paper will explore the solutions and implementation principles of various problems of mobile terminal adaptation.

## One inch

Generally, the physical size of the screen is described in inches, such as that of a computer monitor.`17``22`, mobile phone display`4.8``5.7`All units used are inches.

It should be noted that the above dimensions are the length of the diagonal of the screen:

Inches (`inch`, abbreviated as`in`) In Dutch, the original meaning is thumb. One inch is the width of the thumb of the average person at the bottom of the nail.

Conversion of inches and centimeters:`1 inch = 2.54 cm`

## Resolution

### 2.1 pixels

A pixel is a small square with a specific location and color.

Pictures and electronic screens (cell phones and computers) are made up of numerous small squares with specific colors and specific positions.

Pixels can be used as the smallest unit of pictures or electronic screens.

Let’s use the following`sketch`Open a picture:

Enlarge these pictures to see these pixel points:

Generally speaking, we have two resolutions, screen resolution and image resolution.

### 2.2 Screen Resolution

Screen resolution refers to how many pixels a screen consists of.

The following is`apple`The description of mobile phone resolution on the official website of:

`iPhone XS Max`And`iPhone SE`The resolutions of the are`2688 x 1242`And`1136 x 640`. This indicates the number of pixels the phone has vertically and horizontally.

Of course, high resolution does not mean that the screen is clear. The clarity of the screen is also related to the size.

### 2.3 Image Resolution

What we usually say`Picture resolution`In fact, it means that the picture contains`Number of pixels`For example, the resolution of a picture is`800 x 400`. This means that the number of pixels a picture has vertically and horizontally is`800`And`400`.

The higher the resolution of a picture of the same size, the clearer the picture.

### 2.4 PPI

`PPI(Pixel Per Inch)`: Number of pixels included per inch.

`PPI`Can be used to describe the clarity of the screen and the quality of a picture.

Use`PPI`When describing pictures,`PPI`The higher the picture quality, the higher the usage`PPI`When describing the screen,`PPI`The higher, the clearer the screen.

In the picture above describing the resolution of the mobile phone, we can see:`iPhone XS Max`And`iPhone SE`The`PPI`Respectively`458`And`326`This is enough to prove that the screen of the former is clearer.

Since the cell phone size is the diagonal length of the cell phone, we usually use the following method to calculate it`PPI`:

`iPhone 6`The`PPI`For

Then it contains about`326`Physical pixels.

### 2.5 DPI

`DPI(Dot Per Inch)`: That is, the number of points included per inch.

The dot here is an abstract unit. It can be a screen pixel, a picture pixel or an ink dot of a printer.

At ordinary times you may see the use of`DPI`To describe pictures and screens, at this time`DPI`Should and`PPI`Is equivalent,`DPI`The most commonly used term is used to describe a printer, indicating the number of dots that the printer can print per inch.

When a picture is displayed on the screen, its pixel points are regularly arranged, and each pixel point has a specific position and color.

When using the printer to print, the printer may not print these dots regularly, but use one printing dot after another to present this image, and there will be certain gaps between these printing dots, which is`DPI`Description: Density of printing dots.

In the above image, we can clearly see how the printer uses ink dots to print an image.

So, the printer’s`DPI`The higher the accuracy of the printed image, the more ink dots and time will be consumed.

## Third, the equipment independent pixels

In fact, the pixels we described above are all`Physical pixel`That is, the actual physical unit on the device.

Let’s take a look`Device independent pixel`How did this happen?

Smartphones are developing very fast. A few years ago, we still used phones with very low resolution, such as the white phone on the left below. Its resolution is`320x480`, we can browse the normal text, pictures and so on.

However, with the development of science and technology, low-resolution mobile phones can no longer meet our needs. Soon, a higher resolution screen was born, such as the black cell phone below. Its resolution is`640x940`That’s twice as much as a white cell phone.

In theory, images and text of the same size on a white phone will be scaled twice on a black phone because its resolution has doubled. In this way, isn’t there a higher resolution mobile phone behind, and the page elements will become smaller and smaller?

However, this is not the case. No matter how high the resolution of the smart phones we use now, the proportions of the interfaces they display are basically similar. Jobs in`iPhone4`For the first time at the press conference`Retina Display`The concept of (retina screen) solves the above problems, which also makes it a cross-era mobile phone.

In`iPhone4`Using the retina screen, put the`2x2`When pixels`1`The use of pixels makes the screen look more delicate, but the size of the elements will not change.

If the black mobile phone uses the technology of retinal screen, then the display result should be as follows, for example, the width of the list is`300`A pixel, then in a horizontal line, white mobile phones will use`300`Physical pixels to render it, while black phones actually use`600`Physical pixels to render it.

We must use a unit to tell mobile phones with different resolutions at the same time, what is the size of the display elements on the interface, this unit is the device independent pixels (`Device Independent Pixels`Abbreviations`DIP`Or`DP`. As we said above, the width of the list is`300`In fact, we can say: the width of the list is`300`Each device has independent pixels.

Open`chrome`The developer tool, we can simulate the display of various mobile phone models, each model will display a size, such as`iPhone X`The displayed size is`375x812`In fact`iPhone X`The resolution of the will be much higher than this, here is the device independent pixels.

### 3.1 Device Pixel Ratio

Device pixel ratio`device pixel ratio`Abbreviations`dpr`That is, the ratio of physical pixels to device independent pixels.

In`web`The browser provides us with`window.devicePixelRatio`To help us get`dpr`.

In`css`In, you can use media queries`min-device-pixel-ratio`Distinguish between`dpr`

``@media (-webkit-min-device-pixel-ratio: 2),(min-device-pixel-ratio: 2){ }``

In`React Native`We can also use`PixelRatio.get()`To get`DPR`.

Of course, there are exceptions to the above rules.`iPhone 6、7、8 Plus`The actual physical pixel of is`1080 x 1920`In the developer tool, we can see that its device independent pixels are`414 x 736`, device pixel ratio`3`, the product of the device independent pixel and the device pixel ratio is not equal to`1080 x 1920`, but is equal to`1242 x 2208`.

In fact, the phone will automatically turn`1242 x 2208`A pixel point into`1080 * 1920`We don’t have to care about this process, and`1242 x 2208`Known as the screen`Design pixel`. This is also the basis for our development process.`Design pixel`It will prevail.

In fact, the concept of device pixel ratio only appeared when Apple proposed the retina screen, because before that, mobile devices used physical pixels directly for display.

Then,`Android`Other technical schemes are also used to implement the method.`DPR`Greater than`1`But the principle is similar. Due to`Android`The screen size is very large and the resolution span is very large, unlike Apple, which only has its own fixed equipment and size. Therefore, in order to ensure the display effect of various devices,`Android`According to the pixels per inch of the equipment, the equipment is divided into several sections:

Of course, all of them`Android`The device may not strictly follow the above resolution; each type may correspond to several different resolutions; therefore, each`Android`Mobile phones can determine their own according to a given range`DPR`To have a similar display. Of course, it is only similar. Due to the difference in size and resolution of each device, the independent pixels of the device will not be completely equal, so all kinds of`Android`The equipment still cannot be completely equal on display.

### 3.2 Mobile Development

In`iOS``Android`And`React Native`The style unit under development actually uses device independent pixels.

`iOS`The dimension unit of is`pt`,`Android`The dimension unit of is`dp`,`React Native`There is no specific unit specified in; they are actually device independent pixels.`dp`.

In use`React Native`exploitation`App`At that time,`UI`The prototype diagrams given to us are generally based on`iphone6`The pixel of the given.

In order to adapt to all models, we need to convert physical pixels into device independent pixels when writing styles: for example, if the height of a given element is`200px`(Here`px`Refers to physical pixels, not`CSS`Pixels),`iphone6`The device pixel ratio of is`2`, we give`height`Should be`200px/2=100dp`.

Of course, the best thing is that you can communicate well with the design, all of it`UI`The figures are drawn by independent pixels of the equipment.

We can also use the code (`React Native`) to be carried out`px`And`dp`Conversion of:

``````import {PixelRatio } from 'react-native';

const dpr = PixelRatio.get();

/**
* px to dp
*/
export function pxConvertTodp(px) {
return px / dpr;
}

/**
* dp to px
*/
export function dpConvertTopx(dp) {
return PixelRatio.getPixelSizeForLayoutSize(dp);
}``````

### 3.3 WEB development

Writing`CSS`When, we use the most unit is`px`, i.e.`CSS pixels`When the page scale is`100%`When, one`CSS pixels`Equal to an independent pixel of a device.

but`CSS pixels`It is easy to change, when the user zooms in on the browser,`CSS pixels`Will be magnified, then one`CSS pixels`Will span more physical pixels.

`The zoom factor of the page = CSS pixels/device independent pixels`.

Let’s say two more words here.`Retina`Screen, because I see right in many articles`Retina`Misunderstanding of the screen.

`Retina`Screen is just a marketing term put forward by Apple:

Under the ordinary use distance, the human naked eye cannot distinguish individual pixel points.

Why stress`Under normal use distance`? Let’s look at its calculation formula:

`a`Represents the visual angle of human eyes.`h`Represents the pixel pitch,`d`Represents the distance between the naked eye and the screen. A screen that meets the above conditions can make a single physical pixel invisible to the naked eye.

It cannot simply express resolution and`PPI`, can only express a visual effect.

Having multiple physical pixels render an independent pixel simply`Retina`A technique used by a screen to achieve an effect. Not all`DPR > 1`The screen is`Retina`Screen.

For example: Give you a large screen, even if it’s`PPI`Very high.`DPR`It is also very high. You can see its pixels at close range, which is not counted.`Retina`Screen.

We often see the use of`K`And`P`This unit describes the screen:

`P`Represents the number of pixels in the vertical direction of the screen.`1080P`I.e. vertically`1080`Pixels, Resolution`1920X1080`The screen belongs to`1080P`Screen.

What we usually mean by high definition screen is that the physical resolution of the screen reaches or exceeds`1920X1080`The screen.

`K`On behalf of the horizontal screen there are several`1024`Pixels, generally speaking, horizontal pixels exceed`2048`It belongs to`2K`Screen, horizontal pixels exceed`4096`It belongs to`4K`Screen.

## Iv. viewport

Viewport (`viewport`) represents the currently visible computer graphics area. In`Web`In browser terminology, it is usually the same as the browser window, but does not include the browser’s`UI`, menu bar, etc-that is, the part of the document you are browsing.

Generally speaking, there are three kinds of viewports: layout viewports, visual viewports and ideal viewports, which play a very important role in screen adaptation.

### 4.1 Layout Viewports

Layout viewport (`layout viewport`): When we specify the size of an element as a percentage, its calculated value is calculated by the inclusion block of the element. When this element is the top-level element, it is calculated based on the layout viewport.

Therefore, the layout viewport is the reference window for web page layout, which is located in the`PC`On the browser, the layout viewport is equal to the window size of the current browser (excluding`borders``margins`, scroll bar).

On the mobile side, layout viewports are assigned a default value, mostly`980px`This guarantees that`PC`The web page can be displayed on the mobile phone browser, but it is very small, and users can enlarge the web page manually.

We can do this by calling`document.documentElement.clientWidth / clientHeight`To get the layout viewport size.

### 4.2 Visual Viewport

Visual viewport (`visual viewport`): The area that the user actually sees through the screen.

The visual viewport defaults to the window size of the current browser (including scroll bar width).

When the user zooms on the browser, the size of the layout viewport will not change, so the page layout will not change, but zooming will change the size of the visual viewport.

For example, the user enlarged the browser window`200%`In the browser window`CSS pixels`Will enlarge with the enlargement of the visual viewport, then one`CSS`Pixels span more physical pixels.

Therefore, layout viewports will limit you`CSS`Layout and visual viewports determine what users can see.

We can do this by calling`window.innerWidth / innerHeight`To get the visual viewport size.

### 4.3 Ideal Viewport

The effect of layout viewports displayed on the mobile side is not an ideal effect, so ideal viewports (`ideal viewport`) is born: the ideal size of the website page displayed on the mobile side.

As shown in the above figure, we used this figure when describing the device independent pixels. When the browser debugs the mobile terminal, the pixel size given on the page is the ideal viewport size, and its unit is the device independent pixels.

It was introduced above.`CSS pixels`It was mentioned that`The zoom factor of the page = CSS pixels/device independent pixels`In fact`The zoom factor of the page = ideal viewport width/visual viewport width`More accurate.

Therefore, when the page scale is`100%`At that time,`CSS pixels = device independent pixels`,`Ideal viewport = visual viewport`.

We can do this by calling`screen.width / height`To get the ideal viewport size.

### 4.4 Meta viewport

`<meta>`Element represents those that cannot be determined by other`HTML`Any metadata information represented by one of the meta-related elements, which can tell the browser how to parse the page.

We can use it`<meta>`elementary`viewport`To help us set up viewports, zoom and so on, so that the mobile terminal can get a better display effect.

``<meta name="viewport" content="width=device-width;   initial-scale=1;   maximum-scale=1;   minimum-scale=1;   user-scalable=no;"  >``

Above is`viewport`A configuration of, let’s take a look at their specific meaning:

`Value` Possible value describe
`width` Positive integer or`device-width` In order to`pixels`In pixels, defines the width of the layout viewport.
`height` Positive integer or`device-height` In order to`pixels`(pixels) Defines the height of the layout viewport in units.
`initial-scale` `0.0 - 10.0` Defines the initial page zoom ratio.
`minimum-scale` `0.0 - 10.0` Defines the minimum value for scaling; Must be less than or equal to`maximum-scale`The value of.
`maximum-scale` `0.0 - 10.0` Defines the maximum zoom value; Must be greater than or equal to`minimum-scale`The value of.
`user-scalable` A boolean value (`yes`Or ..`no`) If set to`no`, users will not be able to zoom in or out of the page. The default value is yes.

In order to make the page display better on the mobile side, we must make the layout viewport and the visual viewport equal to the ideal viewport as much as possible.

`device-width`Is equal to the width of the ideal viewport, so set`width=device-width`This is equivalent to making the layout viewport equal to the ideal viewport.

Due to`Initial-scale = Ideal Viewport Width/Visual Viewport Width`So we set up`initial-scale=1;`This is equivalent to making the visual viewport equal to the ideal viewport.

At this time, 1`CSS`Pixel is equal to a device independent pixel, and we also layout based on ideal viewports, so the page layout presented can be roughly similar on various devices.

### 4.6 scaling

Mentioned above`width`You can determine the width of layout viewports, but in fact it is not the only decisive factor for layout viewports. Set`initial-scale`There are also possibilities that affect the layout viewport because the width of the layout viewport is`width`And the visual viewport width.

For example, if the ideal viewport width of a mobile phone is`400px`, settings`width=device-width`,`initial-scale=2`At this time`Visual viewport width = ideal viewport width/initial-scale`That is,`200px`The layout viewport takes the maximum of both, that is`device-width` `400px`.

If set`width=device-width`,`initial-scale=0.5`At this time`Visual viewport width = ideal viewport width/initial-scale`That is,`800px`The layout viewport takes the maximum of both, that is`800px`.

### 4.7 Get Browser Size

The browser provides us with access to the window size`API`There are many, let’s compare them again:

• `window.innerHeight`: Gets the browser visual viewport height (including vertical scroll bars).
• `window.outerHeight`: Gets the height outside the browser window. Indicates the height of the entire browser window, including sidebars, window borders, and borders that resize the window.
• `window.screen.Height`: Get the desired viewport height of the screen, this value is fixed.`Resolution/device pixel ratio of the device`
• `window.screen.availHeight`: The height available for the browser window.
• `document.documentElement.clientHeight`: Gets the browser layout viewport height, including the inner margin, but excluding the vertical scroll bar, border, and outer margin.
• `document.documentElement.offsetHeight`: Includes inner margin, scroll bar, border and outer margin.
• `document.documentElement.scrollHeight`: The minimum width required to fit everything in the viewport without using scroll bars. Measurement methods and`clientHeight`Same: It contains the inner margin of the element, but does not include borders, outer margins, or vertical scroll bars.

## V. 1px problem

In order to adapt to various screens, we usually use device independent pixels to lay out the page when writing code.

While that pixel ratio in the device is great than`1`On the screen, we wrote`1px`In fact, it is rendered by multiple physical pixels, which will appear`1px`On some screens it looks very thick.

### 5.1 border-image

Based on`media`Queries determine that pixels of different devices are different than those given`border-image`

``````.border_1px{
border-bottom: 1px solid #000;
}
@media only screen and (-webkit-min-device-pixel-ratio:2){
.border_1px{
border-bottom: none;
border-width: 0 0 1px 0;
border-image: url(../img/1pxline.png) 0 0 2 0 stretch;
}
}``````

### 5.2 background-image

And`border-image`Similarly, prepare a qualified border background map and simulate it on the background.

``````.border_1px{
border-bottom: 1px solid #000;
}
@media only screen and (-webkit-min-device-pixel-ratio:2){
.border_1px{
background: url(../img/1pxline.png) repeat-x left bottom;
background-size: 100% 1px;
}
}``````

The above two kinds of pictures need to be prepared separately, and the fillet is not very easy to handle, but it can handle most scenes.

### 5.3 Pseudo Class+transform

Based on`media`Query and Judge Different Equipment Pixels to Scale Lines:

``````.border_1px:before{
content: '';
position: absolute;
top: 0;
height: 1px;
width: 100%;
background-color: #000;
transform-origin: 50% 0%;
}
@media only screen and (-webkit-min-device-pixel-ratio:2){
.border_1px:before{
transform: scaleY(0.5);
}
}
@media only screen and (-webkit-min-device-pixel-ratio:3){
.border_1px:before{
transform: scaleY(0.33);
}
}``````

This method can satisfy all kinds of scenes. If fillets need to be satisfied, only pseudo classes need to be added`border-radius`Just.

### 5.4 svg

Above us`border-image`And`background-image`Can be simulated`1px`Border, but using bitmaps, also need external introduction.

With the help of`PostCSS`The`postcss-write-svg`We can use it directly.`border-image`And`background-image`Create`svg`The`1px`Border:

``````@svg border_1px {
height: 2px;
@rect {
fill: var(--color, black);
width: 100%;
height: 50%;
}
}
.example { border: 1px solid transparent;   border-image: svg(border_1px param(--color #00b1ff)) 2 2 stretch;  }``````

After compilation:

``.example { border: 1px solid transparent;   border-image: url("data:image/svg+xml;  charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' height='2px'%3E%3Crect fill='%2300b1ff' width='100%25' height='50%25'/%3E%3C/svg%3E") 2 2 stretch;  }``

The above scheme is recommended by desert in his article. it can basically satisfy all the scenes and does not need external introduction. this is my personal preferred scheme.

### 5.5 Setting viewport

By setting the zoom, let`CSS`Pixels are equal to real physical pixels.

For example, when the device pixel ratio is`3`When, we zoom the page`1/3`Times, at this time`1px`Is equal to a real screen pixel.

``````const scale = 1 / window.devicePixelRatio;
const viewport = document.querySelector('meta[name="viewport"]');
if (!  viewport) {
viewport = document.createElement('meta');
viewport.setAttribute('name', 'viewport');
}
viewport.setAttribute('content', 'width=device-width,user-scalable=no,initial-scale=' + scale + ',maximum-scale=' + scale + ',minimum-scale=' + scale);``````

In fact, the above scheme is earlier`flexible`The scheme adopted.

Of course, there is a price to pay, which means that all layouts on your page are written in physical pixels. This is obviously unrealistic, at this time, we can use`flexible`Or`vw、vh`To help us adapt.

## Six, mobile terminal adaptation scheme

Although we can use independent pixels of the device to ensure that the display effects of each device on different mobile phones are similar, this does not guarantee that they are completely consistent. We need a scheme to make the design draft more perfectly adapted.

### 6.1 flexible scheme

`flexible`The solution is a mobile adaptation solution of Ali’s early open source, quoted`flexible`After that, we will use it uniformly on the page.`rem`To lay out.

Its core code is very simple:

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

`rem`Is relative to`html`Node’s`font-size`To do the calculations.

By setting up`document.documentElement.style.fontSize`The layout standard of the whole page can be unified.

In the above code, the`html`Node’s`font-size`Set as Page`clientWidth`(Layout Viewports)`1/10`, i.e.`1rem`Is equal to the page layout viewport`1/10`, which means that we use later`rem`It is calculated according to the proportion of pages.

At this time, we just need to`UI`The figure is converted to`rem`Just.

In order to`iPhone6`For example: layout viewports are`375px`, then`1rem = 37.5px`At this time`UI`The width of a given element is`75px`(device independent pixel), we just need to set it to`75 / 37.5 = 2rem`.

Of course, every layout is very complicated to calculate, we can use it.`PostCSS`The`px2rem`Plug-ins to help us complete this process.

The following code can ensure that when the page size changes, the layout can be adaptive, when triggered`window`The`resize`And`pageShow`Automatically adjust after an event`html`The`fontSize`Size.

``````// reset rem unit on page resize
if (e.persisted) {
setRemUnit()
}
})``````

Due to`viewport`The company is compatible with many browsers, and the above scheme has now been officially abandoned:

Lib-flexible is a transitional plan that can be abandoned. Whether it is the current version or the previous version, there are certain problems. It is suggested that you start using viewport to replace this scheme.

Let’s look at the most popular ones now.`vh、vw`Plan.

### 6.2 vh and vw schemes

`vh、vw`The scheme refers to the visual viewport width`window.innerWidth`And visual viewport height`window.innerHeight`Divided equally into 100 parts.

Above`flexible`The plan is to imitate this kind of plan, because earlier`vw`It has not been well compatible.

• `vw(Viewport's width)``1vw`Equal to the visual viewport`1%`
• `vh(Viewport's height)`:`1vh`For visual viewport height`1%`
• `vmin`:`vw`And`vh`The smaller value in
• `vmax`: select`vw`And`vh`The larger value in

If the visual viewport is`375px`, then`1vw = 3.75px`At this time`UI`The width of a given element is`75px`(device independent pixel), we just need to set it to`75 / 3.75 = 20vw`.

We don’t need to convert the proportion relationship here, we can use it.`PostCSS`The`postcss-px-to-viewport`Plug-ins help us complete this process. When writing code, we only need to base on`UI`To write the design drawings`px`Unit is enough.

Of course, no plan is perfect.`vw`There are also certain defects:

• `px`Convert to`vw`Not necessarily completely divisible, so there is a certain pixel difference.
• For example, when the container is used`vw`,`margin`Use`px`When, it is easy to cause the overall width to exceed`100vw`, thus affecting the layout effect. Of course, we can also avoid it, such as using`padding`Replace`margin`, combined with`calc()`Function usage, etc …

`iPhoneX`The appearance of the new mobile phone takes the color value to a new height. It cancels the physical keys and changes it into a small black bar at the bottom. However, such changes make it more difficult for developers to adapt to the mobile terminal.

### 7.1 Safety Zone

In`iPhoneX`Since its release, many manufacturers have successively introduced mobile phones with edge screens.

These phones and ordinary phones have made three changes in appearance: rounded corners (`corners`), bangs (`sensor housing`) and small black stripes (`Home Indicator`）。 In order to adapt to these mobile phones, the concept of a safe area was born: a safe area is a visual window that is not affected by the above three effects.

In order to ensure the display effect of the page, we must limit the page to a safe range, but do not affect the overall effect.

### 7.2 viewport-fit

`viewport-fit`It is specially designed for adaptation.`iPhoneX`And the birth of an attribute, it is used to limit how web pages are displayed in a secure area.

`contain`: the visual window completely contains the contents of the web page

`cover`: Web page content completely covers the visual window

By default or set to`auto`And`contain`The effect is the same.

### 7.3 env、constant

We need to properly place the top and bottom in a safe area.`iOS11`Two new ones have been added.`CSS`Function`env、constant`A that sets the distance between the security zone and the boundary.

The inside of the function can be four constants:

• `safe-area-inset-left`: distance of safety zone from left boundary
• `safe-area-inset-right`: distance of safety zone from right boundary
• `safe-area-inset-top`: distance of safety zone from top boundary
• `safe-area-inset-bottom`: distance of safety zone from bottom boundary

Note: We must specify`viweport-fit`These two functions cannot be used until after:

``<meta name="viewport" content="viewport-fit=cover">``

`constant`In`iOS < 11.2`Is effective in the version of,`env`In`iOS >= 11.2`This means that we often have to set them up at the same time to restrict the page to a safe area:

``````body {
}``````

When using the bottom fixed navigation bar, we will set it up for them.`padding`Value:

``````{
}``````

Many viewports have different layouts for horizontal and vertical screens, so we need to detect different styles given in different scenes:

### 8.1 JavaScript detection horizontal screen

`window.orientation`: Gets the screen rotation direction

``````window.addEventListener("resize", ()=>{
if (window.orientation === 180 || window.orientation === 0) {
//Normal direction or screen rotation 180 degrees
Log ('vertical screen');
};
if (window.orientation === 90 || window.orientation === -90 ){
//The screen rotates 90 degrees clockwise or 90 degrees counterclockwise
Log ('horizontal screen');
}
});``````

### 8.2 CSS detection horizontal screen

``````@media screen and (orientation: portrait) {
/* vertical screen ... */
}
@media screen and (orientation: landscape) {
/* horizontal screen ... */
}``````

## Nine, the picture fuzzy problem

### 9.1 Causes

Most of the pictures we usually use belong to bitmaps (`png、jpg ...`), the bitmap is composed of pixel by pixel, each pixel has a specific location and color value:

In theory, each pixel of the bitmap is rendered with one physical pixel on the screen, so as to achieve the best display effect.

And in`dpr > 1`On the screen of, a bitmap pixel may be rendered by multiple physical pixels, however, these physical pixel points cannot be accurately assigned the color of the corresponding bitmap pixel, only approximate values can be taken, so the same picture is in`dpr > 1`The screen will be blurred:

### 9.2 Solution

In order to ensure the quality of the picture, we should render one picture pixel as much as possible for one screen pixel, so, for different`DPR`The screen, we need to show pictures of different resolutions.

In`dpr=2`On the screen of the display double figure`(@2x)`In`dpr=3`The screen of the show three times the figure`(@3x)`.

### 9.3 media inquiries

Use`media`Query and judge different device pixel ratios to display pictures with different precision:

``````.avatar{
background-image: url(conardLi_1x.png);
}
@media only screen and (-webkit-min-device-pixel-ratio:2){
.avatar{
background-image: url(conardLi_2x.png);
}
}
@media only screen and (-webkit-min-device-pixel-ratio:3){
.avatar{
background-image: url(conardLi_3x.png);
}
}``````

Applies only to background maps

### 9.4 image-set

Use`image-set`

``````.avatar {
background-image: -webkit-image-set( "conardLi_1x.png" 1x, "conardLi_2x.png" 2x );
}``````

Applies only to background maps

### 9.5 srcset

Use`img`Tagged`srcset`Property, the browser will automatically match the best display picture according to the pixels per inch:

``````<img src="conardLi_1x.png"
srcset=" conardLi_2x.png 2x, conardLi_3x.png 3x">``````

### 9.6 JavaScript mosaic picture url

Use`window.devicePixelRatio`Obtain the device pixel ratio, traverse all pictures, and replace the picture address:

``````const dpr = window.devicePixelRatio;
const images =  document.querySelectorAll('img');
images.forEach((img)=>{
img.src.replace(".", `@\${dpr}x.`);
})``````

### 9.7 Use svg

`SVG`The full name of is scalable vector diagram (`Scalable Vector Graphics`）。 Unlike bitmap-based pixels,`SVG`It is a description of the shape of the image, so it is essentially a text file with small volume and no distortion no matter how many times it is enlarged.

Except that we manually draw in the code`svg`, we can also use it like bitmap`svg`Picture:

``````<img src="conardLi.svg">

<img src="data:image/svg+xml;  base64,[data]">

.avatar {
background: url(conardLi.svg);
}``````