You must know about mobile terminal adaptation


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

  • 1pxProblem
  • UIFigure perfect adaptation scheme
  • iPhoneXAdaptation plan
  • Horizontal screen adaptation
  • 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,PPIDPIDPDIPDPR, 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.1722, mobile phone display4.85.7All units used are inches.

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

Inches (inch, abbreviated asin) 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


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 followingsketchOpen 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 isappleThe description of mobile phone resolution on the official website of:

iPhone XS MaxAndiPhone SEThe resolutions of the are2688 x 1242And1136 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 sayPicture resolutionIn fact, it means that the picture containsNumber of pixelsFor example, the resolution of a picture is800 x 400. This means that the number of pixels a picture has vertically and horizontally is800And400.

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.

PPICan be used to describe the clarity of the screen and the quality of a picture.

UsePPIWhen describing pictures,PPIThe higher the picture quality, the higher the usagePPIWhen describing the screen,PPIThe higher, the clearer the screen.

In the picture above describing the resolution of the mobile phone, we can see:iPhone XS MaxAndiPhone SEThePPIRespectively458And326This 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 itPPI:

iPhone 6ThePPIFor

Then it contains about326Physical 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 ofDPITo describe pictures and screens, at this timeDPIShould andPPIIs equivalent,DPIThe 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 isDPIDescription: 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’sDPIThe 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 allPhysical pixelThat is, the actual physical unit on the device.

Let’s take a lookDevice independent pixelHow 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 is320x480, 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 is640x940That’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 iniPhone4For the first time at the press conferenceRetina DisplayThe concept of (retina screen) solves the above problems, which also makes it a cross-era mobile phone.

IniPhone4Using the retina screen, put the2x2When pixels1The 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 is300A pixel, then in a horizontal line, white mobile phones will use300Physical pixels to render it, while black phones actually use600Physical 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 PixelsAbbreviationsDIPOrDP. As we said above, the width of the list is300In fact, we can say: the width of the list is300Each device has independent pixels.

OpenchromeThe developer tool, we can simulate the display of various mobile phone models, each model will display a size, such asiPhone XThe displayed size is375x812In factiPhone XThe resolution of the will be much higher than this, here is the device independent pixels.

3.1 Device Pixel Ratio

Device pixel ratiodevice pixel ratioAbbreviationsdprThat is, the ratio of physical pixels to device independent pixels.

InwebThe browser provides us withwindow.devicePixelRatioTo help us getdpr.

IncssIn, you can use media queriesmin-device-pixel-ratioDistinguish betweendpr

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

InReact NativeWe can also usePixelRatio.get()To getDPR.

Of course, there are exceptions to the above rules.iPhone 6、7、8 PlusThe actual physical pixel of is1080 x 1920In the developer tool, we can see that its device independent pixels are414 x 736, device pixel ratio3, the product of the device independent pixel and the device pixel ratio is not equal to1080 x 1920, but is equal to1242 x 2208.

In fact, the phone will automatically turn1242 x 2208A pixel point into1080 * 1920We don’t have to care about this process, and1242 x 2208Known as the screenDesign pixel. This is also the basis for our development process.Design pixelIt 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,AndroidOther technical schemes are also used to implement the method.DPRGreater than1But the principle is similar. Due toAndroidThe 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,AndroidAccording to the pixels per inch of the equipment, the equipment is divided into several sections:

Of course, all of themAndroidThe device may not strictly follow the above resolution; each type may correspond to several different resolutions; therefore, eachAndroidMobile phones can determine their own according to a given rangeDPRTo 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 ofAndroidThe equipment still cannot be completely equal on display.

3.2 Mobile Development

IniOSAndroidAndReact NativeThe style unit under development actually uses device independent pixels.

iOSThe dimension unit of ispt,AndroidThe dimension unit of isdp,React NativeThere is no specific unit specified in; they are actually device independent pixels.dp.

In useReact NativeexploitationAppAt that time,UIThe prototype diagrams given to us are generally based oniphone6The 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 is200px(HerepxRefers to physical pixels, notCSSPixels),iphone6The device pixel ratio of is2, we giveheightShould be200px/2=100dp.

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

We can also use the code (React Native) to be carried outpxAnddpConversion 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

WritingCSSWhen, we use the most unit ispx, i.e.CSS pixelsWhen the page scale is100%When, oneCSS pixelsEqual to an independent pixel of a device.

butCSS pixelsIt is easy to change, when the user zooms in on the browser,CSS pixelsWill be magnified, then oneCSS pixelsWill span more physical pixels.

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

3.4 About Screen

Let’s say two more words here.RetinaScreen, because I see right in many articlesRetinaMisunderstanding of the screen.

RetinaScreen is just a marketing term put forward by Apple:

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

Why stressUnder normal use distance? Let’s look at its calculation formula:

aRepresents the visual angle of human eyes.hRepresents the pixel pitch,dRepresents 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 andPPI, can only express a visual effect.

Having multiple physical pixels render an independent pixel simplyRetinaA technique used by a screen to achieve an effect. Not allDPR > 1The screen isRetinaScreen.

For example: Give you a large screen, even if it’sPPIVery high.DPRIt is also very high. You can see its pixels at close range, which is not counted.RetinaScreen.

We often see the use ofKAndPThis unit describes the screen:

PRepresents the number of pixels in the vertical direction of the screen.1080PI.e. vertically1080Pixels, Resolution1920X1080The screen belongs to1080PScreen.

What we usually mean by high definition screen is that the physical resolution of the screen reaches or exceeds1920X1080The screen.

KOn behalf of the horizontal screen there are several1024Pixels, generally speaking, horizontal pixels exceed2048It belongs to2KScreen, horizontal pixels exceed4096It belongs to4KScreen.

Iv. viewport

Viewport (viewport) represents the currently visible computer graphics area. InWebIn browser terminology, it is usually the same as the browser window, but does not include the browser’sUI, 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 thePCOn the browser, the layout viewport is equal to the window size of the current browser (excludingbordersmargins, scroll bar).

On the mobile side, layout viewports are assigned a default value, mostly980pxThis guarantees thatPCThe 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 callingdocument.documentElement.clientWidth / clientHeightTo 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 window200%In the browser windowCSS pixelsWill enlarge with the enlargement of the visual viewport, then oneCSSPixels span more physical pixels.

Therefore, layout viewports will limit youCSSLayout and visual viewports determine what users can see.

We can do this by callingwindow.innerWidth / innerHeightTo 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 pixelsIt was mentioned thatThe zoom factor of the page = CSS pixels/device independent pixelsIn factThe zoom factor of the page = ideal viewport width/visual viewport widthMore accurate.

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

We can do this by callingscreen.width / heightTo get the ideal viewport size.

4.4 Meta viewport

<meta>Element represents those that cannot be determined by otherHTMLAny 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>elementaryviewportTo 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 isviewportA configuration of, let’s take a look at their specific meaning:

Value Possible value describe
width Positive integer ordevice-width In order topixelsIn pixels, defines the width of the layout viewport.
height Positive integer ordevice-height In order topixels(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 tomaximum-scaleThe value of.
maximum-scale 0.0 - 10.0 Defines the maximum zoom value; Must be greater than or equal tominimum-scaleThe value of.
user-scalable A boolean value (yesOr If set tono, users will not be able to zoom in or out of the page. The default value is yes.

4.5 mobile end adaptation

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-widthIs equal to the width of the ideal viewport, so setwidth=device-widthThis is equivalent to making the layout viewport equal to the ideal viewport.

Due toInitial-scale = Ideal Viewport Width/Visual Viewport WidthSo we set upinitial-scale=1;This is equivalent to making the visual viewport equal to the ideal viewport.

At this time, 1CSSPixel 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 abovewidthYou can determine the width of layout viewports, but in fact it is not the only decisive factor for layout viewports. Setinitial-scaleThere are also possibilities that affect the layout viewport because the width of the layout viewport iswidthAnd the visual viewport width.

For example, if the ideal viewport width of a mobile phone is400px, settingswidth=device-width,initial-scale=2At this timeVisual viewport width = ideal viewport width/initial-scaleThat is,200pxThe layout viewport takes the maximum of both, that isdevice-width 400px.

If setwidth=device-width,initial-scale=0.5At this timeVisual viewport width = ideal viewport width/initial-scaleThat is,800pxThe layout viewport takes the maximum of both, that is800px.

4.7 Get Browser Size

The browser provides us with access to the window sizeAPIThere 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 andclientHeightSame: 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 than1On the screen, we wrote1pxIn fact, it is rendered by multiple physical pixels, which will appear1pxOn some screens it looks very thick.

5.1 border-image

Based onmediaQueries determine that pixels of different devices are different than those givenborder-image

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

5.2 background-image

Andborder-imageSimilarly, prepare a qualified border background map and simulate it on the background.

border-bottom: 1px solid #000;
@media only screen and (-webkit-min-device-pixel-ratio:2){
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 onmediaQuery and Judge Different Equipment Pixels to Scale Lines:

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){
transform: scaleY(0.5);
@media only screen and (-webkit-min-device-pixel-ratio:3){
transform: scaleY(0.33);

This method can satisfy all kinds of scenes. If fillets need to be satisfied, only pseudo classes need to be addedborder-radiusJust.

5.4 svg

Above usborder-imageAndbackground-imageCan be simulated1pxBorder, but using bitmaps, also need external introduction.

With the help ofPostCSSThepostcss-write-svgWe can use it directly.border-imageAndbackground-imageCreatesvgThe1pxBorder:

@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='' 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, letCSSPixels are equal to real physical pixels.

For example, when the device pixel ratio is3When, we zoom the page1/3Times, at this time1pxIs 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 earlierflexibleThe 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 useflexibleOrvw、vhTo 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

flexibleThe solution is a mobile adaptation solution of Ali’s early open source, quotedflexibleAfter that, we will use it uniformly on the page.remTo lay out.

Its core code is very simple:

// set 1rem = viewWidth / 10
 function setRemUnit () {
 var rem = docEl.clientWidth / 10 = rem + 'px'

remIs relative tohtmlNode’sfont-sizeTo do the calculations.

By setting layout standard of the whole page can be unified.

In the above code, thehtmlNode’sfont-sizeSet as PageclientWidth(Layout Viewports)1/10, i.e.1remIs equal to the page layout viewport1/10, which means that we use laterremIt is calculated according to the proportion of pages.

At this time, we just need toUIThe figure is converted toremJust.

In order toiPhone6For example: layout viewports are375px, then1rem = 37.5pxAt this timeUIThe width of a given element is75px(device independent pixel), we just need to set it to75 / 37.5 = 2rem.

Of course, every layout is very complicated to calculate, we can use it.PostCSSThepx2remPlug-ins to help us complete this process.

The following code can ensure that when the page size changes, the layout can be adaptive, when triggeredwindowTheresizeAndpageShowAutomatically adjust after an eventhtmlThefontSizeSize.

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

Due toviewportThe 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、vwPlan.

6.2 vh and vw schemes

vh、vwThe scheme refers to the visual viewport widthwindow.innerWidthAnd visual viewport heightwindow.innerHeightDivided equally into 100 parts.

AboveflexibleThe plan is to imitate this kind of plan, because earliervwIt has not been well compatible.

  • vw(Viewport's width)1vwEqual to the visual viewport1%
  • vh(Viewport's height):1vhFor visual viewport height1%
  • vmin:vwAndvhThe smaller value in
  • vmax: selectvwAndvhThe larger value in

If the visual viewport is375px, then1vw = 3.75pxAt this timeUIThe width of a given element is75px(device independent pixel), we just need to set it to75 / 3.75 = 20vw.

We don’t need to convert the proportion relationship here, we can use it.PostCSSThepostcss-px-to-viewportPlug-ins help us complete this process. When writing code, we only need to base onUITo write the design drawingspxUnit is enough.

Of course, no plan is perfect.vwThere are also certain defects:

  • pxConvert tovwNot necessarily completely divisible, so there is a certain pixel difference.
  • For example, when the container is usedvw,marginUsepxWhen, it is easy to cause the overall width to exceed100vw, thus affecting the layout effect. Of course, we can also avoid it, such as usingpaddingReplacemargin, combined withcalc()Function usage, etc …

VII. Adapting iPhoneX

iPhoneXThe 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

IniPhoneXSince 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-fitIt is specially designed for adaptation.iPhoneXAnd 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 toautoAndcontainThe effect is the same.

7.3 env、constant

We need to properly place the top and bottom in a safe area.iOS11Two new ones have been added.CSSFunctionenv、constantA 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 specifyviweport-fitThese two functions cannot be used until after:

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

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

body {
 padding-bottom: constant(safe-area-inset-bottom);
 padding-bottom: env(safe-area-inset-bottom);

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

 padding-bottom: constant(safe-area-inset-bottom);
 padding-bottom: env(safe-area-inset-bottom);

Eight, horizontal screen adaptation

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 indpr > 1On 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 indpr > 1The 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 differentDPRThe screen, we need to show pictures of different resolutions.

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

9.3 media inquiries

UsemediaQuery and judge different device pixel ratios to display pictures with different precision:

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

Applies only to background maps

9.4 image-set


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

Applies only to background maps

9.5 srcset

UseimgTaggedsrcsetProperty, 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

Usewindow.devicePixelRatioObtain the device pixel ratio, traverse all pictures, and replace the picture address:

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

9.7 Use svg

SVGThe full name of is scalable vector diagram (Scalable Vector Graphics)。 Unlike bitmap-based pixels,SVGIt 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 codesvg, we can also use it like bitmapsvgPicture:

<img src="conardLi.svg">

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

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



I hope you can reach the following points after reading this article:

  • Clarify the Common Concepts of Mobile Terminal Adaptation
  • Understand the principle of mobile terminal adaptation problem, and master at least one solution.

If there are any mistakes in the article, please correct them in the comment area. If this article helps you, please comment and pay attention.

If you want to read more quality articles, please pay attention to me.Github blogYour star✨, praise and attention are the driving force of my continuous creation!

It is recommended to pay close attention to my WeChat public number “code Secret Garden” and push high-quality articles every day so that we can communicate and grow together.