Designs for the front end is very important, but the design draft is the unit of px, and adaptation of h5 units use most now is rem, baidu is the comparative method to realize the old, or to calculate rem value, or rely on the editor plug-in installation transformation, then I will check some information, and then recorded here

Technology stack

  • Vue-cli 3.0: Create projects using scaffolding tools
  • Postcss-pxtorem: a plugin to convert PX to REM

Automatically set the font size of the root node HTML

The rem unit is relative to the font size of the root node, so it can be dynamically changed by setting the font size of the root node

1. Create rem.js file

# Base size
const baseSize = 32
Set the REM function
function setRem () {
  The current page width relative to 750 width scaling ratio can be modified according to your needs.
  const scale = document.documentElement.clientWidth / 750
  Set the font size for the root node of the page
  document.documentElement.style.fontSize = (baseSize * Math.min(scale, 2)) + 'px'
}

# initialization
setRem()
Reset REM when changing the window size
window.onresize = function () {
  setRem()
}
Copy the code

1. Introduce rem.js in main.js

# main.js
import './utils/rem'
Copy the code

After importing the file, you can check whether the HTML has added the font size attribute or the font size has been dynamically changed to determine whether the introduction is successful. In fact, at this point, rem layout is basically completed. H5 ADAPTS dynamically, but in real development it is still necessary to calculate how much REM px is equal to. Next we use PostCSS-pxtoREM to automatically convert PX to the corresponding REM value


Convert pxto the corresponding REM value using postCSs-pxtorem

Install the dependency package PostCSS-pxtorem

npm install postcss-pxtorem --save-dev
Copy the code

Next, configure postCSs-pxtorem

# vue.config.js
module.exports = {
  lintOnSave: true,
  css: {
    loaderOptions: {
      postcss: {
        plugins: [
          require('postcss-pxtorem'({rootValue: 16, // Conversion of the base selectorBlackList: [], // ignore conversion of the regular match propList: [The '*'],}),]}}}}Copy the code

After a lot of crackling above, if nothing goes wrong, can use PX as a unit development

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

body {
	width: 750px;
	height: 1136px;
}
# will be converted toBody {widht: 23.4375 rem; Height: 35.5 rem; }Copy the code