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 - 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,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 display4.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 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
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 followingsketch
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 isapple
The description of mobile phone resolution on the official website of:
iPhone XS Max
AndiPhone SE
The resolutions of the are2688 x 1242
And1136 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 resolution
In fact, it means that the picture containsNumber of pixels
For example, the resolution of a picture is800 x 400
. This means that the number of pixels a picture has vertically and horizontally is800
And400
.
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.
UsePPI
When describing pictures,PPI
The higher the picture quality, the higher the usagePPI
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
AndiPhone SE
ThePPI
Respectively458
And326
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 itPPI
:
iPhone 6
ThePPI
For
Then it contains about326
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 ofDPI
To describe pictures and screens, at this timeDPI
Should andPPI
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 isDPI
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’sDPI
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 allPhysical pixel
That is, the actual physical unit on the device.
Let’s take a lookDevice 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 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 is640x940
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 iniPhone4
For the first time at the press conferenceRetina Display
The concept of (retina screen) solves the above problems, which also makes it a cross-era mobile phone.
IniPhone4
Using the retina screen, put the2x2
When pixels1
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 is300
A pixel, then in a horizontal line, white mobile phones will use300
Physical pixels to render it, while black phones actually use600
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
AbbreviationsDIP
OrDP
. As we said above, the width of the list is300
In fact, we can say: the width of the list is300
Each device has independent pixels.
Openchrome
The developer tool, we can simulate the display of various mobile phone models, each model will display a size, such asiPhone X
The displayed size is375x812
In factiPhone X
The resolution of the will be much higher than this, here is the device independent pixels.
3.1 Device Pixel Ratio
Device pixel ratiodevice pixel ratio
Abbreviationsdpr
That is, the ratio of physical pixels to device independent pixels.
Inweb
The browser provides us withwindow.devicePixelRatio
To help us getdpr
.
Incss
In, you can use media queriesmin-device-pixel-ratio
Distinguish betweendpr
:
@media (-webkit-min-device-pixel-ratio: 2),(min-device-pixel-ratio: 2){ }
InReact Native
We can also usePixelRatio.get()
To getDPR
.
Of course, there are exceptions to the above rules.iPhone 6、7、8 Plus
The actual physical pixel of is1080 x 1920
In 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 2208
A pixel point into1080 * 1920
We don’t have to care about this process, and1242 x 2208
Known as the screenDesign 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 than1
But the principle is similar. Due toAndroid
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 themAndroid
The device may not strictly follow the above resolution; each type may correspond to several different resolutions; therefore, eachAndroid
Mobile phones can determine their own according to a given rangeDPR
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 ofAndroid
The equipment still cannot be completely equal on display.
3.2 Mobile Development
IniOS
、Android
AndReact Native
The style unit under development actually uses device independent pixels.
iOS
The dimension unit of ispt
,Android
The dimension unit of isdp
,React Native
There is no specific unit specified in; they are actually device independent pixels.dp
.
In useReact Native
exploitationApp
At that time,UI
The prototype diagrams given to us are generally based oniphone6
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 is200px
(Herepx
Refers to physical pixels, notCSS
Pixels),iphone6
The device pixel ratio of is2
, we giveheight
Should be200px/2=100dp
.
Of course, the best thing is that you can communicate well with the design, all of itUI
The figures are drawn by independent pixels of the equipment.
We can also use the code (React Native
) to be carried outpx
Anddp
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
WritingCSS
When, we use the most unit ispx
, i.e.CSS pixels
When the page scale is100%
When, oneCSS pixels
Equal to an independent pixel of a device.
butCSS pixels
It is easy to change, when the user zooms in on the browser,CSS pixels
Will be magnified, then oneCSS pixels
Will 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.Retina
Screen, because I see right in many articlesRetina
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 stressUnder 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 andPPI
, can only express a visual effect.
Having multiple physical pixels render an independent pixel simplyRetina
A technique used by a screen to achieve an effect. Not allDPR > 1
The screen isRetina
Screen.
For example: Give you a large screen, even if it’sPPI
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 ofK
AndP
This unit describes the screen:
P
Represents the number of pixels in the vertical direction of the screen.1080P
I.e. vertically1080
Pixels, Resolution1920X1080
The screen belongs to1080P
Screen.
What we usually mean by high definition screen is that the physical resolution of the screen reaches or exceeds1920X1080
The screen.
K
On behalf of the horizontal screen there are several1024
Pixels, generally speaking, horizontal pixels exceed2048
It belongs to2K
Screen, horizontal pixels exceed4096
It belongs to4K
Screen.
Iv. viewport
Viewport (viewport
) represents the currently visible computer graphics area. InWeb
In 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 thePC
On the browser, the layout viewport is equal to the window size of the current browser (excludingborders
、margins
, scroll bar).
On the mobile side, layout viewports are assigned a default value, mostly980px
This guarantees thatPC
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 callingdocument.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 window200%
In the browser windowCSS pixels
Will enlarge with the enlargement of the visual viewport, then oneCSS
Pixels span more physical pixels.
Therefore, layout viewports will limit youCSS
Layout and visual viewports determine what users can see.
We can do this by callingwindow.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 thatThe zoom factor of the page = CSS pixels/device independent pixels
In factThe zoom factor of the page = ideal viewport width/visual viewport width
More 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 / height
To get the ideal viewport size.
4.4 Meta viewport
<meta>
Element represents those that cannot be determined by otherHTML
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>
elementaryviewport
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 isviewport
A configuration of, let’s take a look at their specific meaning:
Value |
Possible value | describe |
---|---|---|
width |
Positive integer ordevice-width
|
In order topixels In 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-scale The value of. |
maximum-scale |
0.0 - 10.0 |
Defines the maximum zoom value; Must be greater than or equal tominimum-scale The value of. |
user-scalable |
A boolean value (yes Or ..no ) |
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-width
Is equal to the width of the ideal viewport, so setwidth=device-width
This is equivalent to making the layout viewport equal to the ideal viewport.
Due toInitial-scale = Ideal Viewport Width/Visual Viewport Width
So we set upinitial-scale=1;
This is equivalent to making the visual viewport equal to the ideal viewport.
At this time, 1CSS
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 abovewidth
You can determine the width of layout viewports, but in fact it is not the only decisive factor for layout viewports. Setinitial-scale
There are also possibilities that affect the layout viewport because the width of the layout viewport iswidth
And the visual viewport width.
For example, if the ideal viewport width of a mobile phone is400px
, settingswidth=device-width
,initial-scale=2
At this timeVisual viewport width = ideal viewport width/initial-scale
That is,200px
The layout viewport takes the maximum of both, that isdevice-width
400px
.
If setwidth=device-width
,initial-scale=0.5
At this timeVisual viewport width = ideal viewport width/initial-scale
That is,800px
The layout viewport takes the maximum of both, that is800px
.
4.7 Get Browser Size
The browser provides us with access to the window sizeAPI
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 andclientHeight
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 than1
On the screen, we wrote1px
In fact, it is rendered by multiple physical pixels, which will appear1px
On some screens it looks very thick.
5.1 border-image
Based onmedia
Queries determine that pixels of different devices are different than those givenborder-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
Andborder-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 onmedia
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 addedborder-radius
Just.
5.4 svg
Above usborder-image
Andbackground-image
Can be simulated1px
Border, but using bitmaps, also need external introduction.
With the help ofPostCSS
Thepostcss-write-svg
We can use it directly.border-image
Andbackground-image
Createsvg
The1px
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, letCSS
Pixels are equal to real physical pixels.
For example, when the device pixel ratio is3
When, we zoom the page1/3
Times, at this time1px
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');
window.document.head.appendChild(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 earlierflexible
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 useflexible
Orvw、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, quotedflexible
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 tohtml
Node’sfont-size
To do the calculations.
By setting updocument.documentElement.style.fontSize
The layout standard of the whole page can be unified.
In the above code, thehtml
Node’sfont-size
Set as PageclientWidth
(Layout Viewports)1/10
, i.e.1rem
Is equal to the page layout viewport1/10
, which means that we use laterrem
It is calculated according to the proportion of pages.
At this time, we just need toUI
The figure is converted torem
Just.
In order toiPhone6
For example: layout viewports are375px
, then1rem = 37.5px
At this timeUI
The 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.PostCSS
Thepx2rem
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 triggeredwindow
Theresize
AndpageShow
Automatically adjust after an eventhtml
ThefontSize
Size.
// reset rem unit on page resize
window.addEventListener('resize', setRemUnit)window.addEventListener('pageshow', function (e) {
if (e.persisted) {
setRemUnit()
}
})
Due toviewport
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 widthwindow.innerWidth
And visual viewport heightwindow.innerHeight
Divided equally into 100 parts.
Aboveflexible
The plan is to imitate this kind of plan, because earliervw
It has not been well compatible.
-
vw(Viewport's width)
:1vw
Equal to the visual viewport1%
-
vh(Viewport's height)
:1vh
For visual viewport height1%
-
vmin
:vw
Andvh
The smaller value in -
vmax
: selectvw
Andvh
The larger value in
If the visual viewport is375px
, then1vw = 3.75px
At this timeUI
The 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.PostCSS
Thepostcss-px-to-viewport
Plug-ins help us complete this process. When writing code, we only need to base onUI
To write the design drawingspx
Unit is enough.
Of course, no plan is perfect.vw
There are also certain defects:
-
px
Convert tovw
Not necessarily completely divisible, so there is a certain pixel difference. - For example, when the container is used
vw
,margin
Usepx
When, it is easy to cause the overall width to exceed100vw
, thus affecting the layout effect. Of course, we can also avoid it, such as usingpadding
Replacemargin
, combined withcalc()
Function usage, etc …
VII. Adapting iPhoneX
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
IniPhoneX
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 toauto
Andcontain
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
Functionenv、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 specifyviweport-fit
These two functions cannot be used until after:
<meta name="viewport" content="viewport-fit=cover">
constant
IniOS < 11.2
Is effective in the version of,env
IniOS >= 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 {
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.padding
Value:
{
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 > 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 indpr > 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 differentDPR
The screen, we need to show pictures of different resolutions.
Indpr=2
On the screen of the display double figure(@2x)
Indpr=3
The screen of the show three times the figure(@3x)
.
9.3 media inquiries
Usemedia
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
Useimage-set
:
.avatar {
background-image: -webkit-image-set( "conardLi_1x.png" 1x, "conardLi_2x.png" 2x );
}
Applies only to background maps
9.5 srcset
Useimg
Taggedsrcset
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
Usewindow.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 codesvg
, we can also use it like bitmapsvg
Picture:
<img src="conardLi.svg">
<img src="data:image/svg+xml; base64,[data]">
.avatar {
background: url(conardLi.svg);
}
References
Summary
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.