preface

Recently, I wrote my third mobile H5 project and prepared to record some practical explorations in the H5 project. One of the biggest differences between mobile H5 development and PC development is probably the issue of responsive layout.

So let’s talk about mobile responsive layout, understand its context, and explore the best solutions available.

The problem

The full text will be discussed and expanded around the following issues:

  • What are the notable points of H5 related pages on mobile terminal compared with PC terminal?
  • What are the solutions for mobile H5 responsive layout?
  • What is REM? How to use it perfectly in a project?
  • Is VH/VW the best solution? What are its advantages and disadvantages?
  • What are common solutions to large open source libraries?
  • How to build a mobile layout solution quickly?

origin

concept

What is H5 technology?

The name H5 itself is an unfortunate name, and at first glance it looks like HTML5, or a level 5 title tag, which can be quite misleading to some people.

For example: one of my backend colleagues, talking about H5 is very simple, I have learned some HTML before, if you take time off, I will write for you.

Am I a face hoodwinked, H5 === HTML?

Now, what is H5 in a search engine? (Quote from Page 1 of Google terms)

It seems that there are many people who think of H5 as HTML, and H5 is a concept that is unique to China, so to foreigners they also think of IT as HTML, so there is the same misunderstanding between foreigners and non-natives.

At present, H5 is a relatively large concept. I think H5 technology is a collection of a series of mobile Web front-end technologies roughly represented by a Venn diagram as follows

We are only talking about the H5 technology in the Web front-end here, and the H5 technology itself is used for the mobile Web page. As the App itself has a container of “Webview”, in which Web front-end codes can be run, Hybrid App technology is derived from the combination of H5 and native App.

General principles of Hybrid App technology

This is the picture I drew to popularize H5 knowledge to my colleagues in the company.

Differences between the Mobile Web and the PC Web

Remember, how did we lay it out on the PC side?

If the browser width is smaller than min-width, scroll directly. And the other one is white space. Set the width of the page to a base width, leaving the rest of the page white.

But will either solution work on mobile?

The width of mobile phones is mostly inconsistent, and there is no way to zoom the window. Scrolling on mobile makes the experience worse, not to mention the basic page display experience is poor compared to the performance of native apps.

What about white space? More not feasible, the mobile phone device itself is small width, and then the basic white space can not see what.

So in order to make the Web feel like a native App, H5 technology came along. Hybird is further derived. Although it is not as good as App performance, it has absolute advantages in hot update and cannot be replaced by native.

Let’s put one of the most basic H5 technologies into practice: mobile responsive layout.

practice

Solution 1: REM + pxToRem

concept

The CSS uses two types of measurement units: absolute and relative.

Absolute unit

px

Relative unit

em
rem
vw
vh

The first pair relative to the font size, the difference is rem relative to the root font, is relatively easy for us to control the overall size, so we can use it to control the entire page zoom.

The latter pair, relative to the size of the window, will play a major role in the next section.

The principle of

  1. Monitor the width of the screen window, assigned by a proportional conversion tohtmlthefont-size. At this point, the root font size varies with the screen width.
  2. willpxConverted toremThere are two kinds of conventional programs. One is to usesass/lessCustom function inpxToRemWrite,pxThe use ofpxToRemFunction conversion torem. The other way is to just write itpx, the compilation process uses plug-ins to convert allrem. suchdomThe size of the element in the screen will change with the screen width.

implementation

  1. Dynamically update the root font size
const MAX_FONT_SIZE = 420

// Define the maximum screen width
document.addEventListener('DOMContentLoaded', () = > {const html = document.querySelector('html')
  let fontSize = window.innerWidth / 10
  fontSize = fontSize > MAX_FONT_SIZE ? MAX_FONT_SIZE : fontSize
  html.style.fontSize = fontSize + 'px'
})
Copy the code
  1. pxrem

pxToRemPlan a

$rootFontSize: 375 / 10;
// Define the function where px is converted to rem
@function px2rem ($px) {
    @return $px / $rootFontSize + rem;
}

.demo {
    width: px2rem(100);
    height: px2rem(100);
}
Copy the code

pxToRemScheme 2

Install the PostCSS-Pxtorem plugin in VuE-CLI3. Other platforms have similar ideas.

const autoprefixer = require('autoprefixer')
const pxtorem = require('postcss-pxtorem')
module.exports = { 
  // ...
  css: {
    sourceMap: true.loaderOptions: {
      postcss: {
        plugins: [
          autoprefixer(),
          pxtorem({
            rootValue: 37.5.propList: [The '*']})]}}}}Copy the code

Click quick Configuration H5 project engineering

Continue to explore postCSS-PxtoREM plug-in source code, see how it is implemented.

function createPxReplace (rootValue, unitPrecision, minPixelValue) {
    return function (m, $1) {
        if(! $1) return m;
        var pixels = parseFloat($1);
        if (pixels < minPixelValue) return m;
        var fixedVal = toFixed((pixels / rootValue), unitPrecision);
        return (fixedVal === 0)?'0' : fixedVal + 'rem';
    };
}
Copy the code

The transformation of PX into REM is mainly this function, of course, there are a lot of configurable parameters, the core principle is similar to our plan 1. The convenience is that you don’t have to add a function every time you write px, and the code is much cleaner.

Should all elements px be converted to REM? That’s not true, px should not be converted to REM in the border, which is another 1px problem, as discussed in the previous article. Avoid converting PX to REM, and capitalize px in the border to PX/ px/px

Please move the 1px adaptation problem to 1px on the mobile terminal

Solution 2: VH + VW

The principle of

vwA unit of window width that varies with width. From this point of view, scheme 1 is actually a “Hack” of Scheme 2, which achieves the effect of scheme 2 by using listener.

implementation

Similarly, postCSS-pxtoREM is configured using the postCSs-pxto-viewPort plugin.

Let’s see if plugins work the same way.

function createPxReplace(opts, viewportUnit, viewportSize) {
  return function (m, $1) {
    if(! $1) return m;
    var pixels = parseFloat($1);
    if (pixels <= opts.minPixelValue) return m;
    var parsedVal = toFixed((pixels / viewportSize * 100), opts.unitPrecision);
    return parsedVal === 0 ? '0' : parsedVal + viewportUnit;
  };
}
Copy the code

Sure enough, even the method name, variable name, code logic, are the same ha ha ha! Who copy who, I will not point out!

Other Solutions

plan defects
1 The percentage Height failure percentage
2 Media Enquiries +metaviewport Different devices have different widths, and the scaling ratio cannot be completely determined
3 flex It still doesn’t solve the width overrun problem

All of the above schemes have fatal defects and are not recommended for mobile terminal layout calculation.

Flex is best used with REM

compatibility

The compatibility of the above two schemes mainly lies in the keywords REM, VH and VW

Rem performance on mobile is an amazing 100%!

Vh VW is still pretty good, with compatibility issues in lower versions of Safari, but it should be a better mobile layout solution.

Open source library solutions

Vant component library

In the Vant component library, px is used as the measurement unit by default. If rem is needed, the plug-in is perfect for it.

For VW scenarios, Vant can also convert PX to VW through plug-ins, and there may be some pothole points for VW.

Ant – design – mobile component library

The Ant-Design-Mobile component library still uses px units

@hd: 1px; // Basic unit

// Font size
// ---
@font-size-icontext: 10 * @hd;
@font-size-caption-sm: 12 * @hd;
@font-size-base: 14 * @hd;
@font-size-subhead: 15 * @hd;
@font-size-caption: 16 * @hd;
@font-size-heading: 17 * @hd;

/ / the rounded
// ---
@radius-xs: 2 * @hd;
@radius-sm: 3 * @hd;
@radius-md: 5 * @hd;
@radius-lg: 7 * @hd;
@radius-circle: 50%;

// Frame size
// ---
@border-width-sm: 1PX;
@border-width-md: 1PX;
@border-width-lg: 2 * @hd;
Copy the code

As with Vant components, it’s up to the developer to decide which solution to use. This is one of the most flexible approaches to open source libraries.

conclusion

Now that you know the ins and outs of the H5 problem, and how to solve the mobile responsive layout problem, if this article solves any of your questions or problems at work, please give it a thumbs up.

Due to the limited technical level, if there is any mistake in the article, please point out in the comment area, thank you!

The previous article solved the 1px problem, and this article solved the reactive layout problem. Next, I will continue to study some summary of H5 trampling. After that, I’ll probably take a look at the latest vue source code and share it. Want to continue to learn more, might as well click a concern!

The summary of some tramps on H5 has been updated