Welcome to visit personal blog website: www.zhuxin.club

1. Introduction

With the popularity of mobile phones, tablets and other mobile devices, the vast majority of web applications now carry out compatible processing of web adaptation between desktop and mobile terminals. Since there are so many different models and resolutions for mobile and desktop devices, it would be too expensive and impractical to create separate websites for these devices and devices, and the boundaries between them would be blurred. Therefore, creating web applications that can adapt to a variety of devices is the basic requirement of Web development today.

Before we get into the specifics of mainstream adaptation, let’s take a look at the following key concepts:

2. Pixels

2.1 Physical Pixels

The physical pixel (also known as device pixel) is a unit of size that we mostly refer to as resolution, such as the screen resolution of computers and mobile devices. A screen is made up of physical pixels. For example, a phone resolution of 1344 X 750 indicates the number of physical pixels in the vertical and horizontal directions of the phone. In general, the number of physical pixels on a screen is fixed in pt.

CSS 2.2 pixel

The unit of PX size used in CSS styles is CSS pixels, and each device screen has its own CSS pixel size. Open the mobile debugging page of Our Chrome browser, and you can see relevant information about the current test device at the top of the corresponding page, as shown in the following example:

Here 375 X 812 represents the CSS pixels of the current device, also known as device independent pixels. When we’re designing a web page, we use CSS pixels, not physical pixels, as the basis for styling mobile pages. That is, when we put a div tag with width=375px and height = 812px on the page, it can fill the entire screen of the current device under the ideal viewport (see below for more information on viewports), regardless of other factors.

2.3 Device pixel ratio

Device Pixel Ratio (DPR) : the Pixel Ratio of the Device. It describes the initial ratio of physical pixels to CSS pixels (device-independent pixels) in an unscaled state. This is the number of physical pixels that can be contained per 1px CSS pixel. The usual calculation formula is DPR = physical pixels/device-independent pixels (CSS pixels). This formula gives you CSS pixels. The higher the DPR, the more refined the display. Apple’s Retina HD display is a classic example. Taking DPR=2.0 as an example, it means that 4(2 X 2) physical pixel points are used as 1(1 X 1) CSS pixel points.

Although the higher THE DPR, the better the screen hd, the higher the DPR, the higher the quality (clarity) requirements for some web display materials (such as images). A common and easy to understand example is when developing a page. For some image resources, the UI will give us image files with a resolution twice or three times the size of the original CSS pixel that should be displayed on the page. These images are designed to be compatible with devices with DPR 2.0 and 3.0.

For example, an image with a resolution of 100 X 100 can be displayed on a browser with CSS pixels of 100px X 100px, and it will look fine on a DEVICE with DPR of 1. However, if the device is DPR =2, i.e. 1css pixel in horizontal or vertical direction corresponds to 2 physical pixels, then only 100/2=50 CSS pixels in horizontal and vertical direction are required to display the image clearly. If the image is still set to 100px by 100px CSS pixels, Each physical pixel of the actual image will be stretched to 2 physical pixels (1CSS pixels) to fit 100px CSS pixels, so the image will look slightly blurry. This can be solved by using a 2x image (200 X 200) with the CSS pixel size set unchanged (100px X 100px).

3. Browser viewport

In layman’s terms, a viewport on a mobile device (technically known as a viewport) is the area of the device’s screen that can be used to display our web pages. The viewports of browsers fall into the following categories:

3.1 Viewport Layout

Layout viewports represent rectangular areas of the entire content layout of a web page. By default, browsers on mobile devices have a viewPort meta tag, which defines a virtual layout viewport to solve the problem of early page display on mobile phones. IOS and Android generally set the default resolution of the viewport to 980px CSS pixels, so the web page on the PC can be rendered on the phone, but the elements look very small. Generally, the PC web page on the mobile device is manually scaled to control the appropriate page display size.

Generally speaking, the size of the layout viewport is the same as the CSS pixel size of the HTML tag of the root element of the page. So it generally passesdocument.documentElement.clientWidth/clientHeightIn order to get. (This value does not change if the HTML element itself is set to width or if the internal element width exceeds the current viewport width)

3.2 Viewports

The viewport, also known as the visual viewport, represents the portion of the rectangular area that is visible in the layout viewport on the current device. Its size varies as the user manually scales the page. When zooming in, the CSS pixels of the page visible are reduced; When zooming out, you see more CSS pixels on the page.

Page scale = width of layout viewport/width of viewport

3.4 Ideal viewport

The default viewport size provided by layout viewports is not an intelligent viewport compatible with multiple devices, so the concept of an ideal viewport is proposed. Before explaining the ideal viewport, it is important to understand the concepts related to layout viewport configuration:

You can set the viewport by adding the meta tag about the viewport to the HTML header tag:

 <meta name="viewport" content="Width = device - width, user - scalable = yes, initial - scale = 1.0, the maximum - scale = 1.0, the minimum - scale = 1.0">
Copy the code
attribute Value range role
width Positive integer or device-width Defines the width of the viewport, in CSS pixels
height Positive integer or device-height Defines the height of the viewport, in CSS pixels
initial-scale 0.0-10.0 Define the initial scaling value
minimum-scale 0.0-10.0 Defines the maximum scaling, which must be less than or equal to the maximum-scale setting
maximum-scale 0.0-10.0 Defines a minimum-scale scale that must be greater than or equal to the minimum-scale setting
user-scalable yes / no Defines whether to allow the user to manually scale the page. The default value is yes

The meta tag code in the example above represents setting an ideal viewport. Indicates that the viewport width of the current layout is the same as the CSS pixel width of the current device and is not scaled by default. The default layout viewport width on all devices is the same as the screen width of the device.

Matters needing attention:

1: Setting the meta tag of the viewport takes effect only on the mobile terminal and does not affect the PC port. The viewport size on the PC is usually fixed to the size of the browser window.

2: If the meta tag of the viewport is not added, the default viewport size of the layout viewport will be used by default (generally 980px CSS pixels), and the default zoom ratio will be used when the content of the web page can be fully displayed without scroll bars.

3: When the initial-scale property is not set, the page will default to show that the viewport width relative to the corresponding value of the width property is fully visible (may be scaled) without horizontal scroll bars.

4: The initial-scale property is generally the scale ratio relative to the value of the width property. When width is not set, the default is the scale ratio relative to the ideal viewport (i.e. device-width).

5: Try not to disable scaling (user-scalable set to no) to avoid inconvenience for visually or mobility impaired users.

4. Adaptation scheme

At present, mobile web adaptation schemes can be divided into two categories: adaptive and responsive

Adaptive: Adaptsive Web Design, which usually has two sets of Web code (or more) for both PC and mobile. Often the functionality and content of the page on mobile may be reduced compared to that on PC. For mobile pages only, it will show the effect of “equal scaling of pages with uniform effect on mobile devices of different sizes”. The percentage adaptation, REM adaptation scheme and VW/WH adaptation scheme mentioned below are the main adaptive practices of mobile terminals.

The following are some specific implementation schemes for mobile terminal adaptation:

4.1 Percentage Adaptation

The main use of % units to write the width of the page elements, in some cases the height of the elements, margins and other styles, according to the real-time size of the visual area adjustment, as possible to adapt to various resolutions, usually using max-width/min-width control size range is too large or too small.

Advantages:

Simple principle, no compatibility problems

Disadvantages:

1: not applicable to complex scenes with many page elements.

2: Due to the large span of device resolution, the percentage of elements is not easy to control, and the problem of element stretching and deformation may occur.

3: The font size cannot be self-adapted.

4: In the CSS, the relative percentage of the inclusion block or reference object rules are not fixed, which easily complicate the layout.

4.2 rem adaptation

The CSS contains px, EM, and REM. Em is a multiple of the font size of the current element (if the current element is not set, use the font size of the parent element). It applies to a few scenarios. Rem, on the other hand, is a multiple of the font size relative to the HTML root element. For example, if the FONT size of HTML is 16px, then 2rem means 32px.

The core implementation process of REM adaptation scheme is to use REM unit in CSS style according to the preset proportion relationship, dynamically change the font size of root element by monitoring the change of viewport size (that is, device resolution), so as to achieve the adaptive effect of equal scale scaling of page elements.

Implementation example:

The UI design is 375px, and an image is 100px wide and 50px high under the design. When writing CSS styles, we still set width=100rem,height=50rem according to the size numbers under the 375 design. Then use the js script to change the root element font size to the desired viewport CSS width / 375, in px.

    const resetRem = () = > {
        const viewportWidth = document.documentElement.clientWidth
        document.documentElement.style.fontSize = viewportWidth / 375 + "px"
    }
 
    resetRem()
    window.onresize = () = > {
        resetRem()
    }
    
Copy the code

Since many developers with years of experience are used to writing PX units, and due to the development of front-end engineering and build tools, webPack plug-ins (such as Px2Rem) are often used to set up and package projects for automatic px to REM conversion.

Advantages:

Good compatibility and adaptive effect

Disadvantages:

1: not pure CSS mobile adaptation scheme, need to introduce JS script, with a certain degree of coupling.

2: Fractional pixels may appear after REM calculations, and the browser will round them when rendering. So there may be some accuracy problems and page display problems

4.3 vw/wh

Vw, VH, Vmax and Vmin are exclusive units of CSS viewport. The specific meanings of each unit are as follows:

Vw: 1vw is equal to 1% of the viewport width, i.e. 100vw is equal to the viewport width

Vh: 1vh is equal to 1% of the viewport height, that is, 100vh is equal to the viewport height

Vmin: Choose the smaller of VW and VH

Vmax: Choose the larger of VW and vH

We usually set the viewport to be the ideal viewport with the meta tag of the viewport, that is, to match the CSS pixel width of the screen device. So 100vw and 100vh are the width and height of the screen. This makes it easier to calculate the proportion of the elements to the design, and convert the size of the design into viewport units, including text, layout height, width, spacing, etc., so that these elements can be adjusted to the viewport size.

Using viewport units To avoid repeating numerous CSS numerical calculations, you can also use similar plug-ins (such as pX-to-viewport) from build tools such as WebPack to uniformly convert px to viewport units

Application scenarios of Vmin and Vmax:

If vw and WH are used to set the font size of elements in the CSS (e.g. 5vw), the font size will be different in portrait and landscape. In general, 100vw is the width of the short side of the screen in portrait and 100vw is the width of the long side of the screen in landscape. As a result, the actual CSS pixel size of font size is inconsistent in portrait and landscape. If we change the font size to vmin instead of vw, this will keep the text size the same in vertical and horizontal screens.

Of course, if you want the text size to be proportional to the current viewport width, and think that the text should be larger in landscape, you can still use VW.

Advantages:

The appearance of viewport unit can almost be regarded as a substitute for REM adaptation scheme, because compared with REM scheme, it is a pure CSS mobile adaptive adaptation scheme without JS script.

Disadvantages:

There are some compatibility issues, Android4.4 is not supported.

Remark:

In practice, the percentages, REM and VW and PX units are not independent of each other and are often used in combination to suit different scenarios

4.4 Responsive design

Responsive Web Design, this adaptation scheme is usually a set of code, multi-application. Is a technical solution for optimizing the visual experience for a variety of resolutions and device performance. Bootstrap, which was very popular years ago, is a very good set of responsive UI frameworks. Mainly through media query, flexible layout and other means to provide scalable page layout effect for different resolutions from small to large from mobile terminal to PC terminal. There are also some differences in how much functional content is presented at different resolutions. But in general, it will follow the principle of keeping the main content forever.

In general, responsive schemes are a subset of adaptive schemes. Both are dedicated to adapting to different devices and improving the user experience.

Four levels of a responsive interface

1. The same page should look comfortable at different sizes and scales;

2. The same page should look reasonable at different resolutions;

3. Experience on the same page should be unified under different operation modes (such as mouse and touch screen);

4, the same page on different types of devices (mobile phones, tablets, computers), interaction should be consistent with the habit

Here are examples of common effects of PC and mobile device layouts in responsive design (PC left, move right) :

Content that can be automatically hidden/partially displayed: for example, large sections of descriptive text displayed on a computer can only be displayed in small amounts or completely hidden on a mobile phone:

Foldable navigation and menus: expand or fold depending on the page size:

Responsive layout design relies heavily on media queries because of its many considerations. Here is an example of media query code:

@media screen and (max-width: 300px) {
    body {
        background-color:lightblue; }}Copy the code

This CSS code indicates that if the current viewport width is less than 300 CSS pixels, the body element changes its background-color to lightblue

There are many other keywords and attributes supported by media query. You can query them by yourself. < span style = “max-device-height” style = “box-sizing: border-box; line-height: 22px;

Max-device-width specifies the CSS pixel width of the screen on the shorter side of the real device.

2, max-width is the CSS pixel width of the current page viewport.

So when the device switches between horizontal and vertical screens, max-width will change, but max-device-width will not change

Responsive design features:

Advantages:

1. Responsive design can provide a user-friendly Web interface. The same layout can be formatted differently on different devices.

2. Responsive in development, maintenance and operation, compared with multiple versions of the cost will be reduced a lot. There is no need to spend a lot of time on the maintenance of the website

3. Easy to change, responsive design is for pages, you can only change the necessary pages, other pages are not affected.

Disadvantages:

1. Responsive design requires a lot of CSS and JS code tailored for different devices, which leads to larger files and slower page loading.

2. In responsive design, pictures, videos and other resources are generally uniformly loaded, which leads to the actual loading of pictures or videos larger than its display requirements on a low-resolution machine, resulting in unnecessary traffic waste and affecting the loading speed;

3. Limitations: Responsiveness is not suitable for some large portals or e-commerce sites. Generally, portals or e-commerce sites have too much content in one interface, which is not easy to control the design style and too much code will affect the operation speed.

5. Optimization of common adaptation problems

5.1 1px pixel problem

As for the classic 1px border line thickening on mobile, the real reason is not DPR (the relationship between physical pixels and CSS pixels) as most people on the web call it. DPR only affects the detail and hd effect of the page, not the size of the pixels. If DPR is the cause, why don’t 2px and 3px border lines get thicker? The real reason for this is illustrated with an example:

The 750px UI design has a 1px border line. When using an equal scale adaptation (such as REM) on a 375px mobile device, the border line should be 0.5px. However, most mobile devices can only display 1px pixels at the smallest, so if the proportion is wrong, the visual perception will be “thicker”.

Bottom line: At the heart of the 1px issue is the minimum displayable CSS pixel for mobile devices, and the latest IOS versions now support 0.5 pixels.

Since most mobile devices do not support the display of pixels less than 1px, how to simulate the display of pixels less than 1px? There are many solutions available online, but here’s one that’s easy to use (for example, 0.5px) :

    .setOnePx {
        position: relative;
    }
    .setOnePx::after{
         position: absolute;
         content: ' ';
         background-color: #e5e5e5;
         display: block;
         width: 100%;
         height: 1px; 
         transform: scale(1.0.5);
         top: 0;
         left: 0; }}Copy the code

5.2 Resetting the default style on the mobile terminal

For user experience optimization on mobile browsers, the default styles of some HTML tags will be changed. The following is a reference example for resetting one side of the style:

 *,::before.::after{
            box-sizing: border-box;
            -webkit-box-sizing: border-box;
            padding: 0;
            margin: 0;
            /* Move the highlight to clear */
            -webkit-tap-highlight-color: transparent;
            tap-highlight-color:transparent;
        }
        body{
            font-size: 14px;
            font-family: "Microsoft Yahei",sans-serif;
            color:# 333
        }
        ul.ol{
            list-style: none;
        }
        a{
            text-decoration: none;
            color:# 333
        }
        input.textarea{
            /* Optimize the appearance of form elements */
            border: none;
            outline: none;
            appearance: none;
            -webkit-appearance: none;
        }
Copy the code

5.3 Image Resource Adaptation

Because of the need for devices compatible with DPR 2.0 and 3.0, it is often necessary to use 2x or 3x resources. However, this can cause devices with a DPR of 1.0 to use higher quality, larger file 2x or 3x resources. Of course, this is not desirable, resulting in a lot of wasted bandwidth. Modern browsers provide a better way to provide images of different sizes depending on the DPR of the device.

1: srcset and sizes for the img element:

<div class="illustration">
<img src="illustration-small.png"
srcset="images/illustration-small.png 1x, images/illustration-big.png 2x"
style="max-width: 500px"/>
</div>
Copy the code

The 1x, 2x in srcset above represent pixel density descriptors, and represent

When the screen’s DPR = 1, use the image/illustrations-small.png

When the screen’s DPR = 2, use the image/illustrations-big.png

If any of the above conditions are not met, the image resource pointed to by the SRC attribute is used by default

The srcset property alone is only suitable for device DPR adaptation and is only suitable for displaying images of the same size as the area. If you want to display different sizes of images on different screens, the srcset property is not sufficient. You must use sizes of sizes to set the image sizes for different devices.

<img srcset="foo-160.jpg 160w, foo-320.jpg 320w, foo-640.jpg 640w, foo-1280.jpg 1280w"
     sizes="(max-width: 440px) 100vw, (max-width: 900px) 33vw, 254px"
     src="foo-1280.jpg">
Copy the code

The value of the SRCest attribute in w in this example represents the original image display size of the image

The value of the sizes property is a comma-separated string, each of which is a media query expression in parentheses, followed by a space, plus the display width of the image, except for the last part.

With srcset and Sizes, the browser gets the display width of the image from sizes based on the width of the current device, and then loads the image from srcset that is closest to that width.

Given that the screen width of the current device is 480px CSS pixels, the code above shows that the browser queries from sizes and the image display width is 33vw (33%), which is equal to 160px. In the srcset property, there happens to be an image with a width of 160px, so load foo-160.jpg. 254px is the default image size if the current device does not meet any of the size criteria

The SIZES attribute must be used with the SRcset attribute. Using the sizes attribute alone is not valid.

2: Picture element and source element

The IMG element uses the srcset and size attributes, respectively, to accommodate pixel density and screen size, but what if you want to accommodate screens of different pixel densities and sizes?

In this case, use the “picture” tag. It is a container tag that internally uses source and IMG to specify images to load in different cases

<picture>
  <source srcset="[email protected], [email protected] 2x"       
          media="(min-width: 990px)">
  <source srcset="[email protected], [email protected] 2x" 
          media="(min-width: 750px)">
  <img srcset="[email protected], [email protected] 2x" 
       alt="Shopify Merchant, Corrine Anestopoulos">
</picture>
Copy the code

In the code above, the picture tag has two source tags and an IMG tag inside it.

The media attribute of the source tag gives the media query expression, and the srcset attribute is the SRcset attribute of the IMG tag and gives the loaded image file. Sizes property is also used here.

The browser determines whether the current device meets the media query expression of the media attribute according to the sequence in which the source tag appears. If so, the image file specified by the SRcset attribute is loaded, and the source tag and img tag are not executed.

The img tag is the image to load by default, in case none of the above sources match.

The Picture tag can also be used to select images in different formats. For example, load Webp images if the current browser supports that format, PNG images otherwise.

<picture>
  <source type="image/svg+xml" srcset="logo.xml">
  <source type="image/webp" srcset="logo.webp"> 
  <img src="logo.png" alt="ACME Corp">
</picture>
Copy the code

In the code above, the type attribute of the tag gives the MIME type of the image, and srcset is the corresponding image URL.

The browser checks to see if the image format specified by the Type attribute is supported in the order in which the source tag appears. If it does, the image is loaded without checking the source tag. In the example above, the image loading priority is SVG, WebP, and PNG.