SoFunction
Updated on 2025-04-04

vue+px2rem implements the example code of adaptive adaptation of large-screen PC terminal (rem adaptation)

Configuration Preface

Project construction: based on vue-cli3, use postcss-px2rem px2rem-loader for rem adaptation

Implementation principle: Every time we package, webpack uses the plug-in postcss-px2rem to help us automatically convert px units into rem units.

px2rem is a plug-in that automatically converts px to rem, helping developers reduce the mutual conversion calculation process between pixels.

There is a pit ahead: Some components of the UI framework use JavaScript to write css as an inline style directly into the html tag. The relevant css will not be read when packaged and adapted, so to configure the relevant style, "!important" is needed in style for overwriting.

Implementation steps

The first step is to install postcss-px2rem and px2rem-loader

Open the command line tool and enter the following command to install the plug-in (of course, it will be faster to install with Taobao mirror cnpm)

npm install postcss-px2rem px2rem-loader --save

The second step is to create a new Util directory in the root directory src.

// Rem etc. adapt to configuration file//Basic sizeconst baseSize = 16
// Set the rem functionfunction setRem () {
  // The scaling ratio of the current page width relative to 1920 width can be modified according to your needs.  const scale =  / 1920
  // Set the font size of the page root node ("(scale, 2)" means that the maximum magnification ratio is 2, which can be adjusted according to actual business needs)   = baseSize * (scale, 2) + 'px'
}
// InitializationsetRem()
// Reset rem when changing the window size = function () {
  setRem()
}

Step 3: Introduce adapter files in

import './util/rem'

Step 4: Configure the plug-in in

// Introduce equivalence adapter plug-insconst px2rem = require('postcss-px2rem')

//Configure the basic sizeconst postcss = px2rem({
  // Base size baseSize, which needs to be the same as in  remUnit: 16
})

// Use Equal Adapter Plugin = {
  lintOnSave: true,
  css: {
    loaderOptions: {
      postcss: {
        plugins: [
          postcss
        ]
      }
    }
  }
}

Summarize

This is the article about vue+px2rem implementing PC-side large-screen adaptation. For more related content on vue+px2rem large-screen adaptation, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!