When it comes to viewPort mobile adaptation, there may be a few questions in mind.

1. Why adapt to mobile devices?

2. What is viewport?

3. How to adapt mobile devices?

I. Purpose of mobile terminal adaptation:

Usually we see the page on the PC is relatively large, on the PC to visit the page is normal display, the default is not scaled, unless manually scaled, the page will be enlarged or reduced to scale display. However, it is different on the mobile end. If a PC page is accessed on the mobile end, pages may be crowded together, layout disorder or horizontal scroll bar, which brings bad experience to users. In addition, when visiting the page on mobile phones with different screen sizes, the page display effect cannot be reasonably displayed. What we expect is that the content displayed on the page is larger when the mobile phone screen is larger, and the page content will be reduced for self-adaptation when the mobile phone screen is small.

Therefore, the purpose of mobile adaptation is to achieve a reasonable display (adaptive) or to maintain a uniform effect on devices of different sizes.

Basic concepts of viewport

1. Viewport usually refers to the part of a window, viewport, or browser (or maybe a Webview in an app) that displays a web page. Viewports on mobile and PC are different. The PC viewport is the browser window area, while on mobile there are three different viewports: layout viewport, visual viewport and ideal viewport

  • Layout viewport: In the CSS layout area of the browser window, the width of the layout viewport limits the width of the CSS layout. In order for websites designed for PC browsers to display properly on mobile devices, browsers on mobile devices will set their default viewPort to 980px or some other value, which is usually much larger than the viewport on mobile browsers, resulting in horizontal scroll bars in the browser

  • Visual viewport: user through the screen to see the area of the page, by the zoom view display content areas, scaling on the mobile end will not change the width of the viewport layout, when smaller screen covering the CSS more pixels, visual viewport, when magnified, the screen cover less CSS pixels, visual viewport smaller.

  • Ideal viewport: In general, this viewport is not really there, it is the ideal layout viewport size for the device, the user does not have to manually zoom to display the page ideal. The ideal width is the width of the browser (screen).

In order to understand it more clearly, I found two easy to understand pictures on the Internet. If the concept of these three viewports is not clear, take a look at the following images to make it clear:

Layout viewport

Visual viewport

2. So how do you set up an ideal viewport? It’s as simple as adding an important piece of code to the HTML header

 <meta name="viewport"content="Width = device - width, user - scalable = no, initial - scale = 1.0, the maximum - scale = 1.0, the minimum - scale = 1.0">	
Copy the code

So this line of code, if you’re familiar with it, or if you’re familiar with it, then the width of the page will match the width of my device. In effect, it sets the desired viewport by setting the width of the layout viewport to the desired viewport (the width of the browser/device screen).

Viewport widths and so on are CSS pixels, so a few basic concepts need to be understood:

  • CSS pixels: Logical pixels used in code to measure the size of content on a page

  • Device pixel: the physical pixel, the unit that controls the display of the device, related to the device and hardware

  • Device-independent pixels: Device-independent logical pixels that, unlike device pixels (physical pixels), are not real.

  • DevicePixelRatio: defines the relationship between devicePixelRatio and device independent pixel ratio window.devicePixelRatio) devicePixelRatio = physical pixel/device independent pixel

  • Resolution: Refers to the total number of vertical and horizontal physical pixels on the screen

3. In addition to the viewport attribute, which is important for setting the behavior of the viewport, there are several other attributes that are used with the meta tag:

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 An integer or decimal.
minimum-scale Defines the minimum scaling that must be less than or equal to the maximum-scale setting An integer or decimal.
maximum-scale Defines the maximum zoom scale, which must be greater than or equal to the minimum-scale setting An integer or decimal.
user-scalable Defines whether to allow the user to manually scale the page. The default value is yes yes/no

Three, adaptation of several schemes:

(1) CSS3 media query: through the way of media query, write CSS styles adapted to different resolution devices

@media screen and (max-width: 320px){ .... } @media screen and (max-width: 375px){.... } @media screen and (max-width: 414px){.... CSS styles for iphone6/7/8 Plus}......Copy the code

Advantages:

  • The method is simple, just modify the CSS file

  • Adjust the screen width in response to the layout without refreshing the page

Disadvantages:

  • Large amount of code, not convenient maintenance

  • You can’t fit all screen sizes, and you need to write multiple CSS styles

(2) Percentage layout scheme: set the percentage of elements. For example, if two divs want to occupy 100% of the width, set the width of one div to 50%. In this way, the width is not fixed, so that it can be adapted to different resolutions

So the question is, who is the percentage of each child element or attribute set according to?

  1. Percentage of child element width, height: The percentage used in the width or height of a child element is relative to its immediate parent element
  2. Margin and padding: both vertical and horizontal are relative to the width of the parent element, regardless of the height of the parent element
  3. Percentage of border-radius: The percentage of border-radius is relative to its own width, regardless of the parent element

Advantages:

  • The width is adaptive and can be adapted at different resolutions

Disadvantages:

  • Percentages are hard to calculate
  • You need to determine the size of the parent because the calculation is based on the size of the parent
  • If percentages are used in each attribute, the attribute relative to the parent element is not unique
  • The height is not easy to set, and it is generally required to be fixed

(3) the rem plan:

  • Rem units: REM is a unit defined only relative to the font size of the browser’s root element (the HTML element). By default, the font size of HTML elements is 12px
  • Adaptation is achieved through REM: The rem unit is determined by the font size of the root element. The font size of the root element provides a baseline. When the page width changes, you only need to change the value of font size, and then the size of the element with rem as the fixed unit will also change. You need to dynamically set the font size of the root HTML element before calculating the rest of the page elements in rem

Control font size JS code

<script type="text/javascript">
    (function() { var deviceWidth = document.documentElement.clientWidth; deviceWidth = deviceWidth < 320 ? 320 : deviceWidth > 640 ? 640 : deviceWidth; Document. The documentElement. Style. FontSize = deviceWidth + / 7.5'px'; }) (); </script>Copy the code

DeviceWidth /7.5 = 1rem deviceWidth/7.5 = 1rem deviceWidth/7.5 = 1rem deviceWidth/7.5 = 1rem deviceWidth/7.5 = 1rem deviceWidth/7.5 Regardless of whether the page width increases or decreases, the viewport width will be equally divided into 7.5 parts, and each part is 1REM. Thus, 1REM represents different sizes in different visual containers, but its proportion in the total viewport width remains unchanged, realizing equal proportion adaptation.

7.5 is not a fixed value here, but can be set to another value, because the design is usually based on the width of iPhone 6/7/8, usually 375 or 750, so for easy calculation, 7.5 can be divisible for later calculation.

Calculate the REM value of the element

.div{ display: flex; align-items: center; justify-content: center; width: 2rem; Height: 0.96 rem; background:#aaa;The font - size: 0.24 rem; }Copy the code

Given a div with a width of 100px, all other attributes can be calculated similarly, based on the set 1rem = 50px, so 100px=2rem. Font-size: 10.333333px; font-size: 10.333333px; font-size: 10.333333px; In addition, if it is expected to display the same amount of fonts under the small screen as the large screen, but due to the proportional scaling of REM, the small screen will have smaller fonts under the small screen, so the better method for font adaptation is to use PX and media query for adaptation.

Advantages:

  • The rem unit is determined by the font size of the root element. As long as the value of font size is changed, the size of the element with REM as the fixed unit will also change in response

Disadvantages:

  • Font size must be controlled by a piece of JS code
  • The JS code that controls font size must be placed before the page is first loaded, and before the CSS style code is introduced.

(4) Vw and VH scheme CSS3 introduces new units vw and VH related to the viewport. Vw represents the width relative to the viewport, and VH represents the height relative to the viewport

unit meaning
vw The viewport width is 100vw relative to the viewport width
vh The viewport width is 100vh relative to the height of the viewport
vmin Smaller values in VW and vh
vmax The larger values in VW and vh

Vw unit conversion: if the viewport width is 100VW, which covers the entire viewport area, 1VW is equivalent to 1% of the entire viewport width, so 1px= 1/375*100 VW, all page elements can be directly calculated and converted into VW units. However, such calculation is similar to the percentage calculation, which is more troublesome.

But there is a great plugin, postCSS-px-to-viewPort, which can preprocess CSS and convert PX units to VW units, but requires some webpack configuration

{
    loader: 'postcss-loader',
    options: {
    	plugins: ()=>[
        	require('autoprefixer')({
        		browsers: ['last 5 versions']
        	}),
        	require('postcss-px-to-viewport')({
        		viewportWidth: 375,
        		viewportHeight: 1334,
        		unitPrecision: 3,
        		viewportUnit: 'vw',
        		selectorBlackList: ['.ignore'.'.hairlines'],
                minPixelValue: 1,
                mediaQuery: false}})]Copy the code

Postcss-px-to-viewport postCSs-px-to-viewPort

unit meaning
viewportWidth Viewport Width (number)
viewportHeight Viewport Height (figure)
unitPrecision Reserved decimal number set (digit)
viewportUnit Sets the unit to convert (string)
selectorBlackList Class name that does not need to be converted (array)
minPixelValue Sets the minimum pixel value (number) to replace
mediaQuery Allows converting PX in media queries (true/false)

Advantages:

  • Specify the width and height of vw\vh relative to the viewport. It is easier to convert px into VW units
  • The postCSs-px-to-viewPort plugin is convenient for unit conversion

Disadvantages:

  • When converting units directly, percentages may appear as decimals, making calculation inconvenient

  • Compatibility – this is supported by most browsers, but not by ie11. A few lower versions of mobile devices are not supported by ios8 or android4.4

Finally, there is a question, since percentage and VW both need to calculate percentage, what is the difference between the two schemes?

unit meaning
% Width, height, etc. are mostly relative to the direct parent element, border-radius, translate, background-size, etc. are relative to themselves
vw Only relative to viewport width

Above, if there are mistakes, welcome to correct!

@ the Author: lj0214