takeaway
Adaptation is often encountered in front-end development, which may encounter a lot of problems, such as:
1px
The problemUI
Figure perfect adaptation schemeiPhone
Adaptation scheme- Landscape adaptation
- Hd image blur problem
- .
Some people may already know how to solve these problems, but the mechanism of the problem and the mechanism of the solution may be unclear or half-understood. In the process of exploring these questions, we will encounter a lot of concepts, such as: pixel, resolution, PPI, DPI, DP, DPR, yanked, and so on, these concepts are often confused.
This article aims to solve these problems
1 inch
In life, we often say how many inches of mobile phone, monitor, in fact, the inch here is the inch, for example: my mobile phone is 6.5 inches of screen, in fact, is to say that the diagonal length of the mobile phone screen is 6.5 inches.
“Inch” (abbreviated as “in”) means “thumb” in Dutch, and an inch is the width of the average person’s thumb at the bottom of their fingernail.
2 the resolution
Usually we say there are two kinds of resolution, one is the screen resolution, the second is the image resolution; Let’s look at pixels before we talk about resolution
2.1 pixels
A pixel can be thought of as a small square with a specific position and color.
We usually see the picture, electronic screen (mobile phone, computer, TV display screen) is a large number of specific color and position of the pixel block composition; The pixel is its smallest constituent unit.
You can open up an image with Sketch and zoom in to see these pixels
2.2 Screen Resolution
Screen resolution refers to the number of pixels on a screen, and we often adjust the resolution of our computer monitors, for example
This is the window for setting the screen resolution. The recommended number is 1366 * 768, which represents the number of pixels in horizontal and vertical resolution.
One thing to note, of course,The resolution of the
High does not mean that the screen is clear, the screen is clear andsize
The relevant.
2.3 Image resolution
Generally speaking, the resolution of the picture refers to the number of pixels in the picture. For example, the resolution of an image is 800 * 400, where 800 means that there are 800 pixels in the horizontal direction, and 400 means that there are 400 pixels in the vertical direction.
The same size
The higher the resolution, the clearer the picture, the screen
2.4 PPI
PPI (Pixel Per Inch) : indicates the number of pixels Per Inch.
Just said, the same size screen, picture, the higher the resolution, the clearer, in fact, PPI can also be used to describe the screen and picture clarity (quality), because it is the premise of the same size to describe the number of pixels.
Calculation formula of PPI:
2.4 DPI
Dot Per Inch (DPI) is an abstract unit of dots Per Inch. It can be a pixel when describing a screen, a picture, or an ink Dot in a printer.
DPI is equivalent to PPI when it’s used to describe pictures and screens, but it’s most commonly used to describe printers, as the number of dots per inch a printer can print.
When the printer prints out the chip, if the DPI is higher, the density of the print points will be higher, the quality of the printed image will be better, and of course, more ink points and printing time will be consumed.
3 Device independent pixel
In fact, all the pixels we mentioned above are pixelsPhysical pixel
That is, the real physical unit on the device.
Let’s look at how Device Indpendent Pixels (DIP or DP) are generated.
The rapid development of smart phones is far beyond our imagination. In the past, we used mobile phones with very low resolution at the beginning, such as the white mobile phone below, whose resolution is 320 * 480. We can browse normal text and pictures on it.
However, with the development of technology, soon, low resolution mobile phones can no longer meet our needs. Then, too soon, came high resolution phones, such as the black phone below, which has a 640 x 940 resolution, which is exactly twice the resolution of the white phone.
In theory, images and text of the same size and resolution (same DPI) should be scaled twice on a black phone because the resolution is twice as high, so the elements of the page will get smaller and smaller on a later phone with a higher resolution.
However, it turns out that no matter how high the resolution is, the proportions of the content displayed are basically the same. 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, using 2 x 2 pixels as one pixel makes the screen look more refined, but the size of the elements doesn’t change.
If the black phone we mentioned above used the retina screen technology, then the display would look something like this. For example, if the list was 300 pixels wide, the white phone would render it at 300 physical pixels horizontally, while the black phone would actually render it at 600 physical pixels.
The question is, how do developers develop? How can different resolutions be unified?
Device Independent Pixels (DIP or DP) are needed to inform developers and devices of different resolutions of the size of the elements displayed on the interface. We said above that the width of the list is 300 pixels, but we can actually say that the width of the list is 300 device independent pixels.
Using Chrome’s Developer tools, we can simulate what each phone looks like. Each model has a size on it. For example, the iPhone X has a 375-by-812 display, but the iPhone X has a much higher resolution.
When we’re developing, we write pixels that are actually device-specific pixels, so there’s a single unit between the developer and the device at each resolution.
3.1 Device pixel ratio
The Device Pixel Ratio, or DPR for short, is the value of the physical pixels to the individual pixels of the Device.
In a browser, you can get the DPR through window.DevicepixelRatio.
In the CSS, you can run the min-device-pixel-ratio command to obtain the DPR.
@media (-webkit-min-device-pixel-ratio: 2), (min-device-pixel-ratio: 2) {}
Copy the code
In React Native, DPR can be obtained by pixelration.get ().
Of course, there are exceptions to the above rule, such as the actual physical pixels of the iPhone 6, 7, and 8 Plus are 1080 * 1920, which we can see in the Developer tools is 414 * 736 device independent pixels, and the device pixel ratio (DPR) is 3. The product of the device independent pixel and the device pixel ratio is not 1080 * 1920, but 1242 * 2208.
In fact, the phone automatically pushes 1242 * 2208 pixels into 1080 * 1920 physical pixels to render, and we don’t have to worry about that. 1242 * 2208 is called the design pixel of the screen, which is the pixel given in the UI prototype. Of course, this is the design pixel that we use in the development process.
The DIP (device pixel ratio) hasn’t been around since Apple introduced the Retina screen, because until then, mobile devices used physical pixels for display.
Android then uses other technologies to achieve screens with a DPR greater than 1, but the principle is similar. Because Android has so many screen sizes and a wide range of resolutions, unlike Apple, which has only a few fixed devices and sizes of its own. So, in order to ensure that the various devices display well, Android devices are divided 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, it is just similar, but due to the differences in size and resolution of various devices, the individual pixels of the devices will not be exactly the same, so it is still not possible to achieve the same display on various Android devices.
3.2 Mobile Development
In IOS, Android, and React Native development, style units are all device-independent pixels.
IOS is in PT and Android is in DP. There is no specific unit specified in React Native. They are both device independent pixel DP.
When developing apps using React Native, the UI typically gives us prototypes based on the physical pixels of the iPhone 6.
In order to fit all models, we need to convert the physical pixels to device independent pixels when writing the style, for example: Given a height of 200px for an element (this is a physical pixel, not a CSS pixel) and the device pixel ratio (DPR) for the iPhone 6 is 2, our development height should be 200px / 2 = 100dp.
Of course, best of all, it communicates well with the design, and all UI diagrams are pixels per 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. What this means is that we can develop directly according to the pixels given by the UI diagram.
But CSS pixels are very easy to change, when the user zooms in on the browser, the CSS pixel will be enlarged, this is a CSS pixel will cross more physical pixels, you will find that the text is bigger and clearer.
Page scale factor = CSS pixels/device independent pixels
3.4 About Screens
A word more about Retina, because I’ve seen a lot of articles that misunderstand Retina.
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 represents the visual Angle, H represents the pixel spacing, and D represents the spacing 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’t express resolution and PPI (Pixel Per Inch) only one visual effect.
Having multiple physical pixels render a single pixel is just a technique that Retian screens use to make it work, not all screens with DPR > 1 are Retina screens.
For example, if you’re given a supersized screen, even if it has a high PPI and a high DPR (Device Pixel Ratio), but at close range you can see the pixels, it’s not Retina.
We often see screens in terms of K and P:
P is the number of pixels in portrait. 1080P is 1,080 pixels in portrait. A screen with a resolution of 1920 * 1080 is a 1080P screen.
What we call a high definition screen is actually a screen with a physical resolution of 1920 * 1080 or more.
K represents the number of 1024 pixels in landscape. Generally speaking, a screen with more than 2048 pixels in landscape is a 2-K screen, and a screen with more than 4096 pixels in landscape is a 4-K screen.
The above is from what you need to know + what you understand about mobile adaptation
4 viewport
Viewport (viewport) refers to the browser window, which is the part of the browser that displays the web page. It does not include the browser UI, menu bar, etc. — it is the user’s viewable area of the web page, which is the part of the document you are viewing. Can be thought of as a container for HTML elements.
On mobile and PC, viewports are different. While a PC viewport is an area of a browser window, on mobile there are three different viewports: layout viewport, visual viewport, and ideal viewport.
Viewport Settings have no impact on PC pages, but are important for mobile pages.
4.1 Layout Viewport
The base window of a webpage layout. On PC browsers, the size of the current browser window (excluding Borders, margins, and scrollbars) can be changed dynamically depending on the window size. On mobile, the layout viewport is given a default value, most of which is 980px. This ensures that PC web pages can be displayed on the mobile browser, but the content will be smaller. Users can manually zoom in on the web page, and the browser will also display a scroll bar as they zoom in. Through the document. The documentElement. ClientWidth/clientHeight web pages in the layout of the standard mode, the size of the viewport and immutable.
4.2 Visual Viewport
The part of the screen the user can see on a mobile device. The visual viewport size can be obtained by window.innerWidth/innerHeight. The visual window can be changed on both PC and mobile terminals. When the window size is adjusted on PC, the size of the visual port will change. When a mobile device, such as a keyboard, pops up, the viewport becomes smaller.
4.3 Ideal ViewPort
Ideal size for your web page to display on mobile. The width of the page is the same as the width of the device. The page zoom factor is the same as the CSS pixel/device independent pixel, which is more accurate than the page zoom factor = ideal viewport width/visual viewport width. So when the page zoom ratio is 100%, CSS pixels = device independent pixels, layout viewport = visual viewport = ideal viewport, we can see a normal comfortable page on the screen, we can use screen.width/height to get the ideal viewport size.
4.4 Meta Viewport
4.4.1 Properties
attribute | meaning | The values |
---|---|---|
width | Defines the width of the viewport in pixels | Positive integer or device width device-width |
height | Defines the height of the viewport in pixels | Positive integer or device-height |
initial-scale | Define the initial scaling value | Whole or decimal number |
minimum-scale | Defines the minimum reduction scale, which must be less than or equal to the maximum-scale setting | Whole or decimal number |
maximum-scale | Defines the maximum magnification scale, which must be greater than or equal to the minimum-scale setting | Whole or decimal number |
user-scalable | Defines whether the user is allowed to manually scale the page. The default value is yes | yes/no |
4.4.2 Basic usage and functions
<meta name = "viewport" content = "width = device-width, initial-scale = 1.0, maximum-scale = 1.0, user-scalable = no" />
Copy the code
The basic setup above:
-
Width = device-width: indicates that the width of the layout viewport is equal to the width of the device
-
Initial-scale = 1: indicates that the initial scale of the page is 1, equivalent to the visual viewport = ideal viewport, 1 CSS pixel is equal to 1 device independent pixel
-
Maximum-scale = 1.0: Indicates that the maximum scale of the page is 1
-
User-scalable = no: Indicates that users are not allowed to scale the page
The viewport property is used to scale the layout viewport to fit the screen width. Widht = device-width is used to set the initial scale of the layout viewport to the device width. And the default is to layout the initial viewport size equal to the device width, which is called the ideal window.
The above content comes from getting a design draft, how do I do mobile development? + some of your own understanding
4.5 Initial Scaling
The width in the meta tag mentioned above can determine the width of the layout 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 width of the layout viewport takes width and the maximum width of the visual viewport.
Such as: Set width = device-width, initial-scale = 2 and set width = device-width to 400px. Device-width: 400px; initial: scale: > 1; layout: viewport = ideal viewport size;
Set width=device-width, initial-scale=0.5, width= ideal viewport/initial-scale= 800px, width= ideal viewport/initial-scale=0.5, width= ideal viewport/initial-scale=0.5, width= ideal viewport/initial-scale=0.5, width= ideal viewport/initial-scale=0.5 Because now layout viewport > Ideal Window
There is a bit of confusion here is why the text is also bigger??
Personal understanding
As the layout viewport becomes larger, a CSS pixel will be displayed across multiple physical pixels, so the text will become larger.
4.6 Obtaining the Browser Size
The browser provides us with a number of apis to get the window size:
-
Window. innerHeight: Gets the height of the browser’s visual viewport (including the vertical scroll bar)
-
Window.outerheight: Gets the height outside the browser window, which is a fixed value, the device resolution/device pixel ratio
-
Window. Screen. AvailHeight: the height of the browser window
-
For the document. The documentElement. ClientHeight browser layout viewport height, including padding, but does not include the vertical scroll bars, borders, and from the outside
-
Document. The documentElement. OffsetHeight: include padding, scroll bars, borders, and from the outside
-
Document. The documentElement. ScrollHeight: in the case of does not use the scroll bar is suitable for all the content the smallest width of the viewport. Measured in the same way as clientHeight, it includes the inner margins of the element, but does not include borders, margins or vertical scroll bars
5 1 px
In order to accommodate various screens, we write code that uses device independent pixels to layout and develop pages.
On screens where the device-independent pixel ratio is 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 0 stretch;
}
}
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 rounded corners, just add border-RADIUS to the pseudo-class.
SVG 5.4
Above, we can simulate 1px border with both border-image and background-image, but we use bitmap, so we need to import it from outside.
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
5.5 set the viewport
Set the zoom so that CSS pixels are equal to the actual physical pixels.
For example: when the device pixel ratio is 3 and we scale the page by 1/3, this is 1px equal to 1 physical 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 cost to doing this, which means that all the layouts on your page have to be written in physical pixels, which means that your page will only have a good user experience on fixed devices, which is obviously not possible. At this time, we can use flexible or VW, VH to help us adapt.
6 Responsive layout
Although we can use device independent pixels to ensure that the page looks similar on each device, this does not guarantee that the display is completely consistent, and we need a solution to make the design fit perfectly.
6.1 rem layout
Flexible is an early open source mobile terminal adaptation solution of Ali. After quoting Flexible, we use REM to layout the page uniformly
6.1.1 Flexible Solution 1
Its core code is very simple:
// set 1rem = viewWidth / 10
function setRemUnit () {
var docEl = document.documentElement
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 HTML node font size to 1/10 of the page’s clientWidth (layout viewport), so 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.
In the case of iPhone 6, if the layout viewport is 375px, 1rem = 37.5px, this is the UI given an element that is 75px wide (device independent pixels), we just need to 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 complete the process.
The following code ensures that the layout ADAPTS when the page size changes, and automatically adjusts the HTML fontSize after the window’s resize and pageShow events are set.
// reset rem unit on page resize
window.addEventListener('resize', setRemUnit)
window.addEventListener('pageShow'.function (e) {
if (e.persisted) {
setRemUnit()
}
})
Copy the code
6.1.2 Flexible Solution 2
Solution 1 is a general solution, but we need to configure the PostCSS px2REM plug-in to help us automatically calculate the conversion of px -> REM, but there are times when we don’t need, don’t need, or can’t use this plug-in. For example, I’m in this situation right now. In a project, only one page needs a responsive implementation, so it is not possible to configure this plug-in for the whole project. We can use the following solution to achieve it, which is convenient for calculation
function setRemUnit () {
var docEl = document.documentElement
// Let's assume that the standalone device pixel of my design is 375 px
var rem = docEl / 3.75
// 1rem = 100px
docEl.style.fontSize = rem + 'px'
}
Copy the code
In fact, this scheme is developed according to the ratio of 1rem = 100px, which is convenient for calculation, for example
My design drawing is 375px individual device pixels, and now I have a div of 75px, so the size code of this div is width = 0.75rem when I develop it, which is very easy to calculate
6.1.3 Flexible Solution 3
The above scheme is developed under the condition of 1:100 which is convenient for calculation. In fact, there is a more convenient way, that is, to develop according to the ratio of 1:1, 1rem = 1px
< font style = “box-sizing: border-box; color: RGB (74, 74, 74); line-height: 22px; font-size: 12px; < span style = “font-size: 12px;
I tried it out and it worked. You can see that your REM Settings are still responsive and the size is right. It is possible that this problem did exist in previous browsers, but no longer exists.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Document</title>
<style>
html {
font-size: 1px;
}
.test {
padding: 1rem;
background: blue;
margin: 1rem;
width: 5rem;
height: 5rem;
}
.text1 {
font-size: 5rem;
}
.text2 {
font-size: 12rem;
}
</style>
</head>
<body>
<! < div size > < div size > < div size > < div size >
<div class = "test"></div>
<div class = "text">I'm test text 1</div>
<div class = "t2">This is Test text 2</div>
</body>
</html>
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.
The two schemes 6.1.2 and 6.1.3 are my own supplement. If there are mistakes, they have nothing to do with the original text
6.2 VW and VH schemes
The solution of VW and VH is to divide the visual viewport width window. InnerWidth and visual viewport height window. InnerHeight into 100 parts.
The flexible scheme above is actually an imitation of this scheme, because earlier VW was not well compatible.
-
Vw (viewport’s width) : 1vw is equal to 1% of the viewport
-
Vh (viewport’s height) : 1vh is 1% of the viewport’s height
-
Vmin: the smaller value in vw and Vh
-
Vmax: Select the larger value in vw and Vh
If the visual viewport is 375px, then 1vw = 3.75px, then the width of an element given by the UI is 75px (device independent pixels) and we just set it to 75/3.75 = 20vw.
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:
-
The conversion of PX to VW may not be completely divisible, so there is a certain pixel difference
-
When vw is used for container and PX is used for margin, the overall width will easily exceed 100vw, thus affecting the layout effect. Of course, we can also avoid, such as using padding instead of margin, resulting in calc() function, not using px units, etc
7 adapter 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: indicates the distance between the security zone and the left border
- Safe-area-inset-right: indicates the distance between the security zone and the border on the right
- Safe-area-inset-top: indicates the distance between the security area and the top border
- Safe-area-inset-bottom: indicates the distance between the security area and the bottom border
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
8 Landscape 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
9 The picture is blurred
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
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
That’s what you need to know about mobile adaptation
These are excerpts from two blogs + some of my own interpretations