My blog original address: original address if the article is helpful to you, your star is the best encouragement to me ~


Brief introduction: In front-end development, static web pages usually need to adapt to different resolution devices, common adaptive solutions include media query, percentage, REM and VW/VH, etc. Starting from px units, this paper analyzes the shortcomings of PX in mobile terminal layout, and then introduces several different adaptive solutions.

  • Px and viewport
  • Media queries
  • The percentage
  • Rem solutions in adaptive scenarios
  • It ADAPTS itself by vw/ VH

1. Px and viewport

In static web pages, we often use pixels (PX) to describe the width, height and positioning of an element. On the PC side, it is generally assumed that the actual length of CSS is fixed by 1px.

So, is px really a device-independent, fixed size unit like the meter and decimeter?

The answer is no. Figure 1.1 and Figure 1.2 below show the display results under PC and mobile respectively. In the web page, we set the font-size to 16px.

Figure 1.1 Display results on PC with font size of 16px

Figure 1.2 The display result when the font-size is 16px on the mobile terminal

From the comparison of the above two images, we can see that the fonts are both 16px, obviously the normal display of Chinese text on THE PC, while the text on the mobile terminal is very small, almost invisible, indicating that 1px in CSS is not a fixed size, we can see directly from the mobile terminal 1px indicates a small length, so the text display is not clear.

So what determines the true length of a 1px CSS?

To clarify this concept let’s first introduce the concept of pixels and viewports

1. The pixel

Pixels are the basis of web layout. A pixel represents the smallest area that a computer screen can display. There are two types of pixels: CSS pixels and physical pixels.

When we use px units in JS or CSS code, we refer to CSS pixels. Physical pixels are also called device pixels, which are related to the device or hardware. The higher the device density, the more physical pixels there are for the same size screen. The following table shows the specific differences between CSS pixels and physical pixels:

CSS pixel An abstract unit for web developers to use in CSS
Physical pixel Depending only on the hardware density of the device, the physical pixels of any device are fixed

So what is the transformation relationship between CSS pixels and physical pixels? In order to understand the transformation relationship between CSS pixels and physical pixels, you must first understand what the viewport is.

2. The viewport

The broad viewport refers to the screen area of the browser display content, and the narrow viewport includes layout viewport, visual viewport and ideal viewport

(1) Layout viewport

The layout viewport defines the default layout behavior of PC web pages on mobile. Because of the larger resolution of PCS, the layout viewport defaults to 980px. In other words, if you do not set the viewport of the web page, the PC web page will be displayed on mobile by default based on the layout viewport. As a result, it’s obvious that a web page rooted in PC can be blurred on mobile when the default layout viewport is used.

(2) Visual Viewport

The visual viewport represents the display area of the web site seen in the browser. Users can change the visual viewport by zooming in and out to view the displayed content of the web page. The definition of the visual viewport is like holding a magnifying glass to observe the same object from different distances. The visual viewport only resembles the content displayed in the magnifying glass. Therefore, the visual viewport does not affect the width and height of the layout viewport.

(3) Ideal viewport

Ideal viewport or should be called “ideal layout viewport” in full, which in mobile devices refers to the resolution of the device. In other words, the ideal viewport or resolution is the best “layout viewport” given the physical pixels of the device.

The most important thing to understand is the concept of an ideal viewport. In mobile, how does an ideal viewport or resolution relate to physical pixels?

In order to clarify the connection between resolution and physical pixels, we introduce a Device Pixel ratio (DPR), which can be written as:

1 DPR = Physical pixels/resolutionCopy the code

In the case of no scaling, a CSS pixel corresponds to a DPR, i.e., no scaling

1 CSS Pixel = Physical pixel/resolutionCopy the code

In addition, in the mobile layout, we can control the layout by using the Viewport meta tag. For example, in general, we can make the mobile layout under the ideal viewport by using the following tag:

<meta id="viewport" name="viewport" content="width=device-width; Initial - scale = 1.0; maximum-scale=1; user-scalable=no;" >Copy the code

Each attribute of the above meta tag is described in detail as follows:

The property name The values describe
width Positive integer Defines the width of the layout viewport in pixels
height Positive integer Defines the height of the layout viewport in pixels, rarely used
initial-scale [0, 10] Initial scale, 1 means no scaling
minimum-scale [0, 10] Minimum scaling
maximum-scale [0, 10] Maximum scale
user-scalable Yes/no Whether to allow manual zooming of the page. Default value is yes

Among them, let’s look at the width attribute. In the layout of mobile terminal, we will call the width setting as device-width in the meta tag, and device-width generally represents the width of resolution. By setting width=device-width, we set the layout viewport as the ideal viewport.

3. Px and adaptive

Above, we learned that when the layout viewport is set as the ideal viewport via the viewport meta tag, 1 CSS pixel can be represented as:

1 CSS Pixel = Physical pixel/resolutionCopy the code

We found that the layout viewport on PC is usually 980px, and on mobile, the iphone6, for example, has a resolution of 375 * 667, which means that the layout viewport is ideally 375px. For example, if we have a visual draft of 750px by 1134px, a CSS pixel on the PC can be calculated as follows:

PC: 1 CSS pixel = physical pixel/resolution = 750/980 = 0.76pxCopy the code

And under the iphone6:

Iphone6:1 CSS pixels = physical pixels/resolution = 750/375 = 2 pxCopy the code

That is, on the PC, a CSS pixel can be represented by 0.76 physical pixels, whereas in the iphone6, a CSS pixel represents 2 physical pixels. In addition, different mobile devices have different resolutions, which means that one CSS pixel can represent different physical pixels. Therefore, if only px is used as the unit of length and width in CSS, the result is that it is impossible to achieve self-adaptation of each end through a set of styles.

Two, media inquiry

As we said earlier, the size of the physical pixel in the CSS file is different for different devices on different ends, so there is no way to use one set of styles to adapt to each end. From this, we can think:

If one set of patterns doesn’t work, can you give each device a different set of patterns to achieve adaptive effects?

The answer is yes.

Using @Media media queries allows you to define different styles for different media types, especially responsive pages, where you can write multiple sets of styles for different screen sizes to achieve adaptive results. For example:

@media screen and (max-width: 960px){ body{ background-color:#FF6699 } } @media screen and (max-width: 768px){ body{ background-color:#00FF66; } } @media screen and (max-width: 550px){ body{ background-color:#6633FF; } } @media screen and (max-width: 320px){ body{ background-color:#FFFF00; }}Copy the code

The above code defines several styles through the media query, and sets the maximum resolution for the style to take effect with max-width. The above code sets different background colors for the screen resolutions 0 to 320px, 320px to 550px, 550px to 768px, and 768px to 960px.

With media queries, we can achieve a responsive layout by writing different styles for different resolution devices, such as setting different background images for different resolution screens. For example, set up @2X figure for small screen mobile phone, set up @3X figure for large screen mobile phone, through the media query can be very convenient to achieve.

The downside of media queries, however, is that multiple sets of style codes can become cumbersome if too many styles need to be changed as the browser size changes.

3. Percentage

In addition to using PX with media queries to create a responsive layout, we can also use the percentage unit “%” to create a responsive layout.

For example, when the width or height of the browser changes, the percentage unit allows the width and height of the components in the browser to change as the browser changes, thus achieving a responsive effect.

To understand the percentage layout, the first questions to understand are:

Whose percentage (%) is a child element in CSS?

Intuitively, we might think that the percentage of the child element is completely relative to the immediate parent element, the height percentage is relative to the height, and the width percentage is relative to the width. This is correct, of course, but according to the box model of CSS, in addition to the height and width properties, there are also padding, border, margin, and so on. What attributes are set to percentages based on the parent element’s attributes? Then there are the percentages in attributes like border-radius and translate, relative to what? Let’s look at it in detail.

1. Specific analysis of percentages

(1) The percentage of height and width of the child element

The percentage used in the height or width of a child element is relative to the child’s immediate parent, width to the parent’s width, and height to the parent’s height. Such as:

<div class="parent">
  <div class="child"></div>
</div>
Copy the code

If:.father{width:200px; height:100px; } .child{ width:50%; height:50%; } displays the effect of:

(2) Top and bottom, left and right

The height of the parent element relative to the direct nonstatic positioning (default positioning), if the percentage is set

Left and right of child elements The width of the parent element relative to the direct nonstatic positioning (default positioning) if the percentage is set.

The display effect is:

(3) the padding

The padding of the child element, if set as a percentage, is relative to the width of the direct parent element, whether vertical or horizontal, regardless of the height of the parent element.

For example:

.parent{
  width:200px;
  height:100px;
  background:green;
}
.child{
  width:0px;
  height:0px;
  background:blue;
  color:white;
  padding-top:50%;
  padding-left:50%;
}
Copy the code

The display effect is:

The child element has an initial width of 0, and the parent element can be extended by using the padding. The blue part of the figure above is a square with a side length of 100px. This means that the padding, if set to a percentage, is relative to the parent element’s width.

(4) margin

As with padding, the same is true of margin. The child element’s margin, if set to a percentage, is relative to the parent element’s width in both vertical and horizontal directions. I won’t give you specific examples here.

(5) the border – the radius

Border-radius is different. If border-radius is set to a percentage, it is the width relative to itself. For example:

  <div class="trangle"></div>
Copy the code

Set border-RADIUS to a percentage:

.trangle{
  width:100px;
  height:100px;
  border-radius:50%;
  background:blue;
  margin-top:10px;
}
Copy the code

The display effect is:

In addition to border-radius, translate, background-size, etc., are all relative to themselves. This will not be an example.

2. Percentage unit layout applications

Percentage units are widely used in layouts. Here is one application.

So if we want to implement a rectangle with a fixed aspect ratio, if we want to implement a rectangle with an aspect ratio of 4:3, we can do that by using the padding property, because the padding, whether it’s vertical or horizontal, is in percentage units relative to the width of the parent element, So we can set the padding-top to the percentage to achieve an adaptive rectangle:

<div class="trangle"></div>
Copy the code

Set the style to be adaptive:

.trangle{
  height:0;
  width:100%;
  padding-top:75%;
}
Copy the code

By setting padding-top: 75%, which is 75% of the width, we set a rectangle with a constant ratio of length, width and height. The effect is shown below:

3. Percentage unit shortcomings

From the above introduction to percentage units, it is easy to see that there are two obvious disadvantages of using all percentage units to achieve a responsive layout:

(1) The calculation is difficult. If we want to define the width and height of an element, it must be converted into percentage units according to the design draft. (2) As can be seen from section 1, if percentage is used in each attribute, the attribute relative to the parent element is not unique. For example, width and height are relative to the width and height of the parent element, while margin and padding are relative to the width of the parent element in both vertical and horizontal directions, and border-RADIUS is relative to the element itself, etc. As a result, the layout problem becomes complicated when we use percentage units.

4. Rem solutions in adaptive scenarios

1. The rem unit

So first of all, let’s see what rem is. Rem is a flexible, extensible unit that is converted into pixels by the browser and displayed. Unlike em units, REM units, regardless of nesting level, are only relative to the font size of the browser’s root element (HTML element). By default, HTML elements have a font-size of 16px, so:

    1 rem = 12px
Copy the code

For calculation purposes, you can usually set the HTML font size to:

HTML {the font - size: 62.5%}Copy the code

In this case:

    1 rem = 10px
Copy the code

2. Implement responsive layout through REM

The size of THE UNIT of REM is determined relative to the font-size of the root element HTML. The font-size of the root element is equivalent to providing a benchmark. When the size of the page changes, only the value of the font-size needs to be changed, so the size of the element with a fixed unit of REM will also change in response. Therefore, if rem is used to achieve a responsive layout, it only needs to dynamically change the font-size according to the size of the view container.

function refreshRem() {
    var docEl = doc.documentElement;
    var width = docEl.getBoundingClientRect().width;
    var rem = width / 10;
    docEl.style.fontSize = rem + 'px';
    flexible.rem = win.rem = rem;
}
win.addEventListener('resize', refreshRem);
Copy the code

The above code divides the view container into 10 parts, and the font-size is represented by a tenth of the width. Finally, by executing this code in the header tag, we can dynamically define the size of the font-size, so that 1rem represents different sizes in different visual containers. The rem fixed unit can be used to adapt the layout of different containers.

3. Rem2px and px2rem

If rem units are used in a responsive layout, there is a problem with conversion. Rem2px means converting rem units into PX units. However, if REM is multiplied by the corresponding font-size, it can be converted into PX units. A more common application is Px2REM, which is the conversion from PX to REM.

For example, given a visual sketch of 750px (physical pixels), if we want to use REM to represent all the layout units, a relatively stupid way is to multiply all the elements such as height and width by the corresponding proportion. Now convert the visual sketch into REM units, and then use REM to represent each one. Another convenient solution is to use px to represent the size of the elements in CSS, and then, after writing the CSS code, convert all the PX units in the CSS file into REM units.

The principle of Px2REM is also simple. The key is to preprocess CSS files in px units, and then change all px units into REM units. This can be done in two ways:

1) WebPack Loader

npm install px2rem-loader
Copy the code

In the Webpack configuration file:

module.exports = {
  // ...
  module: {
    rules: [{
      test: /\.css$/,
      use: [{
        loader: 'style-loader'
      }, {
        loader: 'css-loader'
      }, {
        loader: 'px2rem-loader',
        // options here
        options: {
          remUni: 75,
          remPrecision: 8
        }
      }]
    }]
  }
Copy the code

}

2) Use the PostCSS Plugin in WebPack

npm install postcss-loader
Copy the code

In the WebPack plugin:

var px2rem = require('postcss-px2rem'); module.exports = { module: { loaders: [ { test: /\.css$/, loader: "style-loader!css-loader!postcss-loader" } ] }, postcss: function() { return [px2rem({remUnit: 75})]; }}Copy the code

4. Examples of REM layout applications

The MOBILE terminal page of netease News uses REM layout. The specific example is as follows:

5. Disadvantages of REM layout

With REM units, you can achieve a responsive layout, especially with the introduction of the corresponding postCSS plug-in, which eliminates the calculation of PX to REM in the design. Rem unit is also used in some foreign websites. The disadvantages, or minor defects, of REM to realize layout here are:

In a reactive layout, you must use JAVASCRIPT to dynamically control the root element’s font-size.

This means that there is a certain degree of coupling between CSS styles and JS code. You must put the code that changes the font size before the CSS style.

V. Adaptive by VW/VH

1. What is VW/VH?

Css3 introduces a new unit vw/ VH, which is related to the view window. Vw represents the width relative to the view window, and VH represents the height relative to the view window. In addition to VW and VH, there are two related units vmin and vmax. The specific meaning of each unit is as follows:

unit meaning
vw Relative to the width of the window, the window width is 100vw
vh The window height is 100vh relative to the height of the window
vmin Smaller values in vw and VH
vmax Large values in vw and VH

Here we find that the width and height of the Windows are 100vw / 100vh, so vw or vh, or vw for short, is very similar to percentage units. The difference between vw and % is:

unit meaning
% Most are relative to ancestor elements, but also relative to themselves (border-radius, translate, etc.)
vw/vh Relative to the size of the window

From the comparison, we can find that the unit of VW is similar to the unit of percentage, but there is a difference. Previously, we introduced the difficulty in converting the unit of percentage. Here, VW is more like the “ideal unit of percentage”. At any level, in terms of vw units, 1VW is equal to one hundredth of the width of the view.

2. Vw unit conversion

Similarly, if we want to convert px to VW units, it’s as simple as determining the window size of the view (layout viewport). If we set the layout viewport to a resolution, such as an iPhone 6/7 with a 375*667 resolution, then px can be converted to VW in the following way:

1px is equal to 1/375 times 100 vwCopy the code

In addition, you can also use the corresponding postCSS plug-in to do an automatic conversion of preprocessed CSS, postcss-px-to-viewport can automatically convert PX to VW. The default parameters for postcss-px-to-viewport are:

var defaults = {
  viewportWidth: 320,
  viewportHeight: 568, 
  unitPrecision: 5,
  viewportUnit: 'vw',
  selectorBlackList: [],
  minPixelValue: 1,
  mediaQuery: false
};
Copy the code

By specifying the width and height of the window, and the conversion accuracy, you can convert px to VW.

3. Compatibility with VW/VH units

Check out support for VW units in various browser versions at https://caniuse.com/.

From the figure above, we can see that most browsers support VW units, but IE9-11 does not support Vmin and vmax. Considering that vmin and vmax units are not commonly used, VW units are well supported in most advanced browsers, but Opera browser does not support VW units overall. Vw is not recommended if you need a layout compatible with the Opera browser.

Summary: This article describes the units commonly used in layouts, such as PX, %, REM, vw, etc., and the advantages and disadvantages of different units in responsive layouts.