How to perform mobile terminal adaptation?

Reference: Mobile front-end adaptation plan (summary)-interview focus

Generalize

  • Through CSS3 media queries, namely media queries
  • flex layout
  • rem + viewport zoom
  • rem way

1、media queries

Execute different css codes by querying the width of the device, and finally achieve the configuration of the interface.

@media screen and (max-width: 600px) { /*当屏幕尺寸小于600px时,应用下面的CSS样式*/
  /*你的css代码*/
}

2. Flex flexible layout

Reference: meta name="viewport" content="width=device-width,initial-scale=1.0" What does it mean?

  • The viewport is fixed:<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
  • initial-scale: The zoom level of the visible area when the page is displayed for the first time. A value of 1.0 means that the page is displayed in its actual size without any zoom; maximum-scale users can zoom in on the page, and 1.0 will prohibit users from zooming in to the actual size. Up; user-scalable: whether the page can be zoomed, no zooming is prohibited
  • The height is fixed, the width is adaptive, and the element uses px as the unit
  • As the screen width changes, the page will also change

3. Rem + viewport zoom

Set the rem value according to the screen width. Elements that need to be adapted use rem as the unit, and elements that do not need to be adapted still use px as the unit.
Thoroughly understand the difference between
the unit px, em, and rem in css. The principle of implementation is: enlarge the page by dpr times according to rem, and then set the viewport to 1/dpr.
dpr definition : device pixel ratio (dpr) = device pixel (resolution) /Device-independent pixels (screen size)
For example, if the dpr is 3, the whole page will be enlarged 3 times, 1px (css unit) is 3px (physical pixels) by default, and then the viewport is set to 1/3, so that the whole page is retracted to its original size. Realize HD

4. Rem implementation

  • The viewport is fixed:<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
  • The remreference value is controlled by code (the actual size of the design is 720px width), which is actually rem + dpr
!function (d) {
    var c = d.document;
    var a = c.documentElement;
    var b = d.devicePixelRatio;
    var f;

    function e() {
      var h = a.getBoundingClientRect().width, g;
      if (b === 1) {
        h = 720
      }
      if(h>720) h = 720;//设置基准值的极限值
      g = h / 7.2;
      a.style.fontSize = g + "px"
    }

    if (b > 2) {
      b = 3
    } else {
      if (b > 1) {
        b = 2
      } else {
        b = 1
      }
    }
    a.setAttribute("data-dpr", b);
    d.addEventListener("resize", function () {
      clearTimeout(f);
      f = setTimeout(e, 200)
    }, false);
    e()
  }(window);

Guess you like

Origin blog.csdn.net/weixin_43912756/article/details/108456930