There is no denying the importance of restoring blueprints in front-end development, and rem is still the most widely used. However, many people still live in the slash-and-burn era, either calculating REM values themselves or relying on editors to install plug-ins to convert them.

And the goal of this paper is through a series of configuration, in the development can directly use the size of the design map development, the project for us to automatically compile, into REM.

Technology stack

  • Vue-cli: Create the project using the scaffolding tool.
  • Postcss-pxtorem: a plugin to convert PX to REM.

Automatically set the root nodehtmlthefont-size

Since the REM unit is relative to the font size of the root node, the REM size can be dynamically changed by setting the font size of the root node.

Principle online there are many articles to share, here is not specific explanation.

1, create,rem.jsfile

A lot of people who write widgets like this routinely add closures, which are unnecessary. In ES6, each file is a separate module.

Const baseSize = 32 // set the rem functionfunction setRem() {// The zoom ratio of the current page width to 750 width can be modified according to your needs. Const scale = document. DocumentElement. ClientWidth / 750 / / set the page root node font size document. The documentElement. Style. FontSize = (baseSize * Math.min(scale, 2)) +'px'} // initializesetRem() // Resets Rem window.onresize = when changing the window sizefunction () {
  setRem()
}

Copy the code

2, inmain.jsThe introduction ofrem.js

import './utils/rem'
Copy the code

After importing the file, check the HTML node of the page to see if font size is automatically added.

Note: after completing this step, which is to realize the REM layout, we still need to calculate the corresponding REM value to develop the actual development.

Next we will configure webPack to automatically convert PX to the corresponding REM value.

configurationpostcss-pxtoremAutomatically convert PX to REM

1, install,postcss-pxtorem

$ npm install postcss-pxtorem -D
Copy the code

2. Change the root directory.postcssrc.jsfile

Find the plugins property to add pxtoREM Settings

"postcss-pxtorem": {
  "rootValue": 32."propList": ["*"], // Note: If you are using a third-party UI such as VUX, you need to configure the selector to be ignored and not converted. // The rule is a string contained in class, for example in VUX all class prefixes are weui-. It can also be re."selectorBlackList": ["weui-"]}Copy the code

After following the above configuration of the project, you can directly use the PX unit development in development.

For example, if the design is 750 * 1136, you can write it directly on the page

body {
	width: 750px;
	height: 1136px;
}
Copy the code

Will be converted to

Body {widht: 23.4375 rem; Height: 35.5 rem; }Copy the code

Note: This method supportsimport.vueA single filestyle. Temporary does not supportstyleThe use of@import url();

—End—