preface

In front end projects, it’s inevitable that you will run into this problem. If you build a page based on the UI design, the display scale may be normal, but if you scale the page, or if you port the page to another screen size, the UI will be distorted.

The usual approach is to do media queries, but I’m not doing a lot of projects at the moment and want to take a new approach to screen adaptation

The following are my personal adaptations for vUE projects, which I tested when using the Ant-Design-Vue and Element-UI component libraries.

However, this method does not change the line style. For example, the label of the element-UI form component adds the line style. In this case, this method cannot be adapted by the following method, so you need to solve this problem by yourself.

Although we adapted it, we recommend using REM as a unit for CSS writing.

Here’s the screen adaptation I used

1. Install the following dependencies

npm install postcss-px2rem px2rem-loader --save
Copy the code

2. Create an rem.js equivalence file in the root directory SRC to directly copy the following code

// REM equal match configuration file
// Base size
const baseSize = 16;
// Set the rem function
function setRem() {
  // The zoom ratio of the current page screen resolution to 1280 width can be modified according to your needs
  const scale = document.documentElement.clientWidth / 1280;
  // Set the font size of the root node of the page (" math.min (scale, 3) "means the maximum zoom ratio is 3, which can be adjusted according to actual business requirements)
  document.documentElement.style.fontSize = `${baseSize * Math.min(scale, 3)}px`;
}
/ / initialization
setRem();
// Resets rem when changing the window size
window.onresize = () = > {
  setRem();
};
Copy the code

3. Import the adaptation file in main.js

4. Modify the vue. Config. Js

Less does not need to be replicated. You only need to copy postCSS

// Introduce equal ratio adaptors
const px2rem = require('postcss-px2rem');

// Configure the base size
const postcss = px2rem({
  // the baseSize baseSize should be the same as in rem.js
  remUnit: 16});module.exports = {
  css: {
    loaderOptions: {
      less: {
        javascriptEnabled: true,},postcss: {
        plugins: [
          postcss,
        ],
      },
    },
  },
};
Copy the code

end

Good luck with your development