takeaway

Mobile terminal adaptation is often encountered in our development, which may encounter a lot of problems:

  • 1pxThe problem
  • UIFigure perfect adaptation scheme
  • iPhoneXAdaptation scheme
  • Landscape adaptation
  • Hd image blur problem
  • .

The above problems may have been known in development, but the rationale for the problem and the rationale for the solution may be unclear. In the process of solving these problems, we tend to encounter so many concepts: pixel, resolution, PPI, DPI, DP, DIP, DPR, viewport, etc., can you really distinguish the meaning of these concepts?

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

A,”

Generally, the physical size of the screen is described in inches. For example, 17 and 22 of computer monitors, 4.8 and 5.7 of mobile phone monitors are all used in inches.

Note that the above dimensions are the diagonal length of the screen:

“Inch” (abbreviated as “in”) means thumb in Dutch, and an inch is the width of the average person’s thumb at the bottom of the nail.

The conversion between inches and centimeters: 1 inch = 2.54 centimeters

Two, resolution

2.1 pixels

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

Pictures, electronic screens (mobile phones, computers) are made up of countless small squares with a specific color and a specific location.

A pixel can be the smallest unit of a picture or electronic screen.

Here’s an image using Sketch:

Zoom in on these images to see the pixels:

There are usually two kinds of resolution, the screen resolution and the image resolution.

2.2 Screen Resolution

Screen resolution refers to the number of pixels that make up a screen.

Here’s what Apple’s website says about the phone’s resolution:

The iPhone XS Max and iPhone SE have 2688 x 1242 and 1136 x 640 resolutions, respectively. This represents the number of pixels the phone has vertically and horizontally.

Of course, high resolution does not mean a clear screen, screen clarity is also related to size.

2.3 Image resolution

When we talk about the resolution of an image, we actually mean the number of pixels in the image. For example, the resolution of an image is 800 x 400. This means that the image has 800 pixels vertically and 400 pixels horizontally.

For the same size image, the higher the resolution, the clearer the image.

2.4 PPI

Pixel Per Inch (PPI) : Indicates the number of pixels Per Inch.

PPI can be used to describe the sharpness of the screen and the quality of an image.

When using PPI to describe pictures, the higher the PPI, the higher the image quality. When using PPI to describe the screen, the higher the PPI, the clearer the screen.

In the picture above describing the phone’s resolution, we can see that the PPI of the iPhone XS Max and iPhone SE is 458 and 326, respectively, which is enough to prove that the former’s screen is sharper.

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

? \frac{\ SQRT {horizontal pixel dots ^2+ Vertical pixel dots ^2}}{size}?

The PPI of the iPhone 6 is 13342+75024.7=325.6 \frac{\ SQRT {1334^2+750^2}}{4.7}=325.64.713342+7502 =325.6, which is about 326 physical pixels per inch.

2.5 DPI

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

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

You might see DPI used to describe pictures and screens, but it should be equivalent to PPI. The most common use of DPI is to describe a printer. DPI is the number of dots per inch a printer can print.

When an image is displayed on the screen, its pixels are arranged in a regular order, with each pixel assigned a specific position and color.

When a printer is used for printing, the printer may not print out the dots regularly, but use the dots one by one to present the image, and there will be a certain gap between the dots. This is what DPI describes: the density of the dots.

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

Therefore, the higher the DPI of the printer, the more detailed the print, which also consumes more ink and time.

Three, the device independent pixel

In fact, the pixels described above are physical pixels, the actual physical units on the device.

Here’s a look at how device independent pixels are generated:

Smart phones are developing very fast. Until a few years ago, we had very low resolution phones, like the white phone on the left below, 320×480 resolution, and we could browse normal text, pictures and so on.

However, with the development of technology, low resolution mobile phones can no longer meet our needs. Soon, higher resolution screens were introduced, like the black phone below, which has a 640×940 resolution, which is exactly twice the resolution of a white phone.

In theory, the same size image and text on a white phone will be scaled twice as large on a black phone because it has twice the resolution. So, won’t the higher resolution phones come later, and the page elements become smaller and smaller?

However, that’s not the case. The smartphones we use today, no matter how high the resolution, display basically the same proportions of interfaces. The Retina Display, first unveiled by Steve jobs at the launch of the iPhone4, solves this problem and makes it a generational device.

In the retina screen used by the iPhone4, the 2×2 pixels are used as one pixel to make the screen look more refined, but the size of the elements remains the same.

If the black phone uses the retina screen technology, the display would look something like this. For example, if the width of the list is 300 pixels, the white phone would render it at 300 physical pixels on a horizontal line, while the black phone would actually render it at 600 physical pixels.

We need to tell phones of different resolutions at the same time what the size of the elements they display on the screen are. These units are Device Independent Pixels, or DIP or DP. We said above that the width of the list is 300 pixels, but we could actually say: the width of the list is 300 device independent pixels.

Using Chrome’s Developer tools, we can simulate the display of various phone models. Each model displays a size. For example, the iPhone X displays a size of 375×812, but the actual iPhone X is much higher resolution.

3.1 Device pixel ratio

Device Pixel ratio, abbreviated as DPR, is the ratio of the physical pixels to the individual pixels of the device.

On the Web, browsers provide us with window.DevicepixelRatio to help us get DPR.

In the CSS, you can query the min-device-pixel-ratio and distinguish DPR by using media:

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

In React Native, we can also use pixelratives.get () to get DPR.

Of course, there are exceptions to the above rule. The actual physical pixels of the iPhone 6, 7, 8 Plus are 1080 x 1920, as we can see in the developer tools: Its device independent pixel is 414 x 736, and the device pixel ratio is 3. The product of device independent pixel and device pixel ratio is not equal to 1080 x 1920, but is equal to 1242 x 2208.

In fact, the phone automatically pushes 1242 x 2208 pixels into 1080 x 1920 physical pixels to render, and we don’t have to worry about that process. 1242 x 2208 is called the design pixels of the screen. This is also the design pixel that we use during development.

In fact, the device pixel ratio hasn’t been around since Apple came up with the retina screen, because until then, mobile devices used physical pixels for display.

Android also uses other technical solutions to achieve a screen with a DPR greater than 1, but the principle is similar. Android has a wide range of screen sizes and resolutions, unlike Apple, which has its own set of devices and sizes. So, in order to ensure that the various devices display well, Android divides the devices into several segments based on their pixel density:

Of course, all Android devices don’t necessarily adhere to the above resolution, each type may have several different resolutions, so each Android phone can determine its OWN DPR based on a given range and thus have a similar display. Of course, just similar, due to the size and resolution of different devices, the individual pixels of the devices will not be exactly the same, so the various Android devices are still not exactly equal in the presentation.

3.2 Mobile Development

In iOS, Android, and React Native development style units are actually device independent pixels.

IOS is in pt and Android is in DP. There is no specific unit specified in React Native, but they are both device independent pixel DP.

When developing apps using React Native, the UI usually gives us a prototype based on the iphone6’s pixels.

For all models, we need to convert the physical pixels to device-independent pixels when we write the style: for example, if we give an element a height of 200px(where px refers to physical pixels, not CSS pixels) and the iphone6 has a device pixel ratio of 2, we give a height of 200px/2=100dp.

Of course, best of all, you can communicate with the design, and all the UI diagrams are pixel by pixel on the device.

We can also convert px and DP in React Native code:

import {PixelRatio } from 'react-native';

const dpr = PixelRatio.get();

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

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

3.3 WEB Development

The unit we use most often when writing CSS is the PX, or CSS pixel. When the page is scaled at 100%, one CSS pixel equals one device independent pixel.

But CSS pixels can be easily changed. When the user zooms in on the browser, the CSS pixels will be enlarged, and a CSS pixel will span more physical pixels.

Page scale factor = CSS pixels/device independent pixels.

3.4 About Screens

A word more about the Retina screen, because I’ve seen a lot of misunderstandings about the Retina screen in articles.

Retina screen is just a marketing term apple has come up with:

At ordinary usage distances, the human eye cannot distinguish individual pixels.

Why emphasize the common use distance below? Let’s look at the formula:

? a=2arctan(h/2d) ?

A represents the visual Angle of the human eye, H represents the pixel spacing, and D represents the distance between the naked eye and the screen. A screen meeting the above conditions can make a single physical pixel invisible to the naked eye.

It can not express resolution and PPI alone, but can only express visual effects in one way.

Having multiple physical pixels render a single pixel is just one technique that Retina screens use to achieve the effect. Not all screens with a DPR > 1 are Retina screens.

For example, if I give you a super-sized screen, even though it has a high PPI, a high DPR, and you can see the pixels at close range, it’s not Retina.

We often see the units K and P used to describe screens:

P is the number of pixels in portrait, 1080P is 1080 pixels in portrait, and a 1920X1080 resolution screen is a 1080P screen.

What we call a high definition screen is actually a screen with a physical resolution of 1920X1080 or higher.

K represents how many 1024 pixels the screen has in landscape. Generally speaking, if the landscape pixel is more than 2048, it belongs to 2K screen, and if the landscape pixel is more than 4096, it belongs to 4K screen.

Fourth, viewport

The viewport represents the area of the computer graphics that is currently visible. In Web browser terms, usually the same as the browser window, but not the browser UI, menu bar, etc. — that part of the document you’re looking at.

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

4.1 Layout of viewports

Layout viewport: When we specify the size of an element as a percentage, it is calculated from the size of the element’s containing blocks. When the element is the top level element, it is calculated based on the layout viewport.

So, the layout viewport is the base window for a web page layout. On a PC browser, the layout viewport equals the current browser window size (borders, margins, scrollbars not included).

On mobile, the layout viewport is given a default value, mostly 980px, which ensures that PC web pages can be rendered on the mobile browser, but is small enough that users can manually zoom in.

We can through a call to the document. The documentElement. ClientWidth/clientHeight viewport size for layout.

4.2 Visual port

Visual Viewport: The area that the user actually sees through the screen.

The visual viewport defaults to the current browser window size (including the scrollbar width).

When the user zooms the browser, the size of the layout viewport does not change, so the page layout remains the same, but zooming changes the size of the visual viewport.

For example, if the user enlargs the browser window by 200%, the CSS pixels in the browser window will enlarge as the visual viewport enlargs, and a CSS pixel will span more physical pixels.

So, the layout viewport limits your CSS layout and the visual viewport determines exactly what the user can see.

We can get the visual viewport size by calling window.innerWidth/innerHeight.

4.3 Ideal viewport

Layout viewports are not ideal for mobile display, so the Ideal Viewport was born: the ideal size for web pages to display on mobile.

As shown in the figure above, which we used to describe device independent pixels, the pixel size given on the page when the browser is debugging the mobile is the ideal viewport size in unit of device independent pixels.

As mentioned above in CSS pixels, the page zoom factor = CSS pixels/device-independent pixels. In fact, it is more accurate to say that the page zoom factor = ideal viewport width/visual viewport width.

So, when the page scale is 100%, CSS pixels = device-independent pixels and ideal viewport = visual viewport.

We can get the ideal viewport size by calling screen.width/height.

4.4 Meta viewport

The
element represents any metadata information that cannot be represented by one of the other HTML meta-related elements, and it tells the browser how to parse the page.

We can use the viewport of the
element to help us set the viewport, zoom, etc., so that the mobile end 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;">
Copy the code

Above is a configuration of the viewport, let’s see what they mean:

Value Possible values describe
width Positive integers ordevice-width In order topixels(pixel) defines the width of the layout viewport.
height Positive integers ordevice-height In order topixels(pixel) defines the height of the layout viewport.
initial-scale 0.0-10.0 Define the initial page zoom ratio.
minimum-scale 0.0-10.0 Define the minimum value of scaling; Must be less than or equal tomaximum-scaleThe value of the.
maximum-scale 0.0-10.0 Define the maximum scale; Must be greater than or equal tominimum-scaleThe value of the.
user-scalable A Boolean value (yesorno) If you set it tonoUsers will not be able to zoom in or out of the web page. The default value is yes.

4.5 Mobile Adaptation

In order to make the page look good on mobile, we must make the layout viewport and visual viewport as equal to the ideal viewport as possible.

Device-width equals the width of the ideal viewport, so setting width=device-width equals the layout viewport equal to the ideal viewport.

Since initial-scale= ideal viewport width/visual viewport width, we set initial-scale=1; It’s equivalent to making the visual viewport equal to the ideal viewport.

At this point, one CSS pixel is equal to one device individual pixel, and we’re laying out the page based on the ideal viewport, so the layout of the page will be roughly similar across devices.

4.6 zoom

Width determines the width of the viewport. In fact, it is not the only determinant of the layout viewport. Setting the initial scale can also affect the layout viewport, because the layout viewport width takes the maximum width and visual viewport width.

Such as: Set width=device-width, initial-scale=2 and set width=device-width to 400px. Device-width: 400px; device-width: 400px;

If width=device-width, initial-scale=0.5, the visual viewport width= ideal viewport width/initial-scale= 800px, and the maximum value of the layout viewport is 800px.

4.7 Obtaining the Browser Size

There are many apis that browsers provide for us to get the window size. Here’s a comparison:

  • window.innerHeight: Gets the height of the browser visual viewport (including the vertical scroll bar).
  • window.outerHeight: Gets the height outside the browser window. Represents the height of the entire browser window, including the sidebar, window edge, and border to resize the window.
  • window.screen.Height: gets the ideal viewport height of the screen. This value is fixed.Device resolution/device pixel ratio
  • window.screen.availHeight: The available height of the browser window.
  • document.documentElement.clientHeight: Gets the viewport height of the browser layout, including margins, but not vertical scroll bars, borders, and margins.
  • document.documentElement.offsetHeight: Includes margin, scroll bar, border, and margin.
  • document.documentElement.scrollHeight: The minimum width required to fit all content in the viewport without scrollbars. Measurement method andclientHeightSame: It contains the inner margin of the element, but does not include the border, margin, or vertical scroll bar.

5. 1px problem

In order to fit various screens, we write code that uses device independent pixels to lay out the page.

On device screens with pixel ratios greater than 1, the 1px we wrote is actually rendered by multiple physical pixels, which causes 1px to look thick on some screens.

5.1 border – image

Based on media query, judge different device pixel ratios to give different border-images:

       .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 0stretch; }}Copy the code

5.2 background-image

Similar to the border-image, prepare a qualified border background image 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; }}Copy the code

Both of the above require separate images, and the rounded corners are not easy to work with, but they can handle most scenes.

5.3 Pseudo-class + Transform

Based on media query, different devices are judged to scale the pixel alignment 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); }}Copy the code

This method can meet various scenarios. If you need to meet the requirement of rounded corners, you only need to add border-RADIUS to the pseudo-class.

SVG 5.4

Both border-image and background-image can simulate a 1px border, but they are bitmaps and need to be imported.

With PostCSS’s postcss-write-SVG we can create 1px borders for SVG directly using the border-image and background-image:

@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; }
Copy the code

The compiled:

.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; }
Copy the code

The above scheme, which Is recommended by Desert in his article, works for almost all scenarios and does not require external introductions, which is my personal favorite.

5.5 set the viewport

Set the scaling to make the CSS pixels equal to the actual physical pixels.

For example, when the device pixel ratio is 3 and the page is scaled 1/3, 1px equals one true screen pixel.

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

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

Of course, there is a price to pay for this, which means that all the layouts on your page have to be written in physical pixels. This is obviously unrealistic. In this case, we can use flexible or VW or VH to help us adapt.

Vi. Mobile terminal adaptation scheme

Although we can use device independent pixels to ensure that devices will look similar on different phones, this does not guarantee that they will look exactly the same, and we need a solution to make the design fit perfectly.

6.1 flexible solutions

Flexible is an early open source mobile terminal adaptation solution of Ali. After referring to Flexible, we use REM for layout on the page.

Its core code is very simple:

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

Rem is calculated relative to the font size of the HTML node.

We by setting up the document. The documentElement. Style. FontSize can unify the entire page layout standards.

In the code above, we set the font size of the HTML node to 1/10 of the page’s clientWidth(layout viewport), which means that 1rem is equal to 1/10 of the page’s layout viewport, which means that the rem we use later is calculated in terms of page scale.

At this time, we only need to convert the graph from UI into REM.

Take the iPhone6 as an example: the layout viewport is 375px, so 1rem = 37.5px. When the UI is given an element that is 75px wide (device independent pixels), we just set it to 75/37.5 = 2rem.

Of course, it’s tedious to calculate each layout, and we can use PostCSS’s px2REM plug-in to help us with this process.

The following code ensures that the layout ADAPTS when the page size changes, automatically adjusting the HTML fontSize when the window’s resize and pageShow events are triggered.

  // reset rem unit on page resize
window.addEventListener('resize', setRemUnit)window.addEventListener('pageshow'.function (e) {
    if (e.persisted) {
      setRemUnit()
    }
})
Copy the code

This scheme is now officially deprecated because the Viewport unit is compatible with many browsers:

Lib-flexible is a transition solution that can be abandoned, but there are some issues with both the current and previous versions. I suggest you start using viewport instead.

Let’s take a look at the most popular VH and VW schemes.

6.2 VH and VW schemes

Vh and VW solutions divide visual viewport width window. InnerWidth and visual viewport height window. InnerHeight into 100 parts.

The flexible scheme above mimics this scheme, as vw was not well compatible in the early days.

  • vw(Viewport's width):1vwEqual to the visual viewport1%
  • vh(Viewport's height) : 1vhFor visual viewport height1%
  • vmin : vwvhSmaller value in
  • vmaxSelection:vwvhLarger value in

If the visual viewport is 375px, then 1vw = 3.75px, then the UI gives an element a width of 75px (device independent pixels), we just need to set it to 75/3.75 = 20vw.

We don’t have to do this by ourselves. We can use the PostCSs-px-to-viewport plugin for PostCSS. When writing code, we only need to write px units according to the design drawing given by the UI.

Of course, no solution is perfect, and VW also has some drawbacks:

  • pxConverted tovwIt’s not exactly divisible, so it’s a pixel difference.
  • For example, when a container is usedvw.marginusingpxIt is easy to cause the overall width to exceed100vw, thus affecting the layout effect. Of course, we can also avoid, such as usingpaddingInstead ofmarginAnd combined with thecalc()Function usage and so on…

7. Fit iPhoneX

The iPhoneX took the look of the phone to a new level, eliminating physical buttons in favor of a small black bar at the bottom, but the change made it more difficult for developers to adapt to mobile.

7.1 Security Zones

After the release of the iPhoneX, a number of manufacturers have released phones with edge screens.

These phones have the same three exterior changes as normal phones: rounded corners (corners), bangs (Sensor housing) and small black Indicators (Home Indicators). To accommodate these phones, the concept of a secure zone was born: a visible window that is immune to the above three effects.

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

7.2 the viewport – fit

Viewport-fit is a property created specifically for the iPhoneX that restricts how web pages are displayed within a secure zone.

Contain: The visual window contains all the content of the web page

Cover: The content of the web page completely covers the visible window

By default, or set it to Auto and contain.

7.3 env, constant

We need to put the top and bottom of the security zone reasonably, iOS11 added two CSS functions env, constant, used to set the distance between the security zone and the border.

There can be four constants inside a function:

  • safe-area-inset-left: The distance between the security zone and the left border
  • safe-area-inset-right: The distance between the security zone and the right border
  • safe-area-inset-top: The distance between the security zone and the top boundary
  • safe-area-inset-bottom: The distance between the security zone and the bottom boundary

Note: We must specify viweport-fit to use these two functions:

<meta name="viewport" content="viewport-fit=cover">
Copy the code

Constant works on iOS < 11.2, and env works on iOS >= 11.2, which means we tend to set them both at the same time, restricting pages to secure zones:

body {
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}
Copy the code

When using the bottom fixed navigation bar, we want to set the padding for them:

{
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}
Copy the code

Eight, horizontal screen adaptation

Many viewports will display different layouts for landscape and portrait, so we need to detect different styles given in different scenes:

8.1 JavaScript detects landscape screen

Window. Orientation: Gets the screen rotation direction

window.addEventListener("resize".() = >{
    if (window.orientation === 180 || window.orientation === 0) { 
      // Rotate the screen 180 degrees in the normal direction
        console.log('portrait');
    };
    if (window.orientation === 90 || window.orientation === -90) {// Turn the screen 90 degrees clockwise or 90 degrees counterclockwise
        console.log('landscape'); }});Copy the code

8.2 The CSS Detects the Landscape Screen

@media screen and (orientation: portrait) {
  / * vertical screen... * /
} 
@media screen and (orientation: landscape) {
  / * landscape... * /
}
Copy the code

Nine, picture fuzzy problem

9.1 Possible Causes

Most of the images we use are bitmaps (PNG, JPG…). , bitmap is composed of pixels, each pixel has a specific position and color value:

In theory, each pixel of the bitmap is rendered with one physical pixel on the screen for the best display.

However, on a screen with DPR > 1, one pixel of the bitmap may be rendered by multiple physical pixels. However, these physical pixels cannot be accurately assigned the corresponding color of the bitmap pixel, and only approximate values can be taken, so the same image will be blurred on the screen with DPR > 1:

9.2 Solution

In order to ensure the quality of the image, we should render one image pixel as much as possible from one screen pixel, so we need to show different resolution images for different DPR screens.

For example, display the double graph (@2x) on the screen of DPR =2 and the triple graph (@3x) on the screen of DPR =3.

9.3 media query

Use media queries to determine different device pixel ratios to display images 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); }}Copy the code

Applies only to background images

9.4 the image – set

Use the image – set:

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

Applies only to background images

9.5 srcset

Using the srcset attribute of the img tag, the browser automatically matches the best display image based on pixel density:

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

Copy the code

9.6 JavaScript splicing image URL

Use windows. devicePixelRatio to get the devicePixelRatio, traverse all the images, and replace the image address:

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

9.7 using SVG

SVG stands for Scalable Vector Graphics. Unlike bitmaps, which are pixel-based, SVG is a shape description of an image, so it is essentially a text file, small in size and without distortion no matter how many times it is magnified.

In addition to manually drawing SVG in code, we can also use SVG images like bitmaps:

<img src="conardLi.svg">

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

.avatar {
  background: url(conardLi.svg);
}
Copy the code

reference

  • 99 designs.com/blog/tips/p…
  • www.w3cplus.com/css/vw-for-…
  • Aotu. IO/notes / 2017 /…

summary

Hopefully, after reading this article, you have achieved the following points:

  • Clarify the common concepts of mobile terminal adaptation
  • Understand the mechanism of mobile adaptation problems and at least one solution

Feel free to correct any mistakes in the comments section, and if this post has helped you, feel free to like or follow.

For more great articles, you can follow me on github blog, and your star✨, like and follow is what keeps me creating!

I recommend you to follow my wechat public account [Code Secret Garden] and push high-quality articles every day. We communicate and grow together.

We are the r&d team of Bytedance Interactive Entertainment, including Douyin short video, Douyin Volcano version, TikTok, Faceu, Xiaoyan, cut and so on. As of January 2020, Douyin daily active users (DAUs) have exceeded 400 million, and continue to maintain high growth. You will support product development and related architecture, and each line of code will affect millions of users.

Class of 2021: DRZUM5Z

Website delivery: job.toutiao.com/s/JR8SthH