How to adapt the screen fonts and overall layout of different resolutions on the PC side of the vue project (2)

1. Font adapts to screen fonts as the resolution changes

First understand that the conversion between rem and px
is relative to the root element. This means that we only need to determine a reference value on the root element. The reference value can be set according to your own needs. We know that the default font size (font-size) of the browser is 16px, let's look at the conversion relationship between some px units and rem:

|  px  |     rem       |
------------------------
|  12  | 12/16 = .75   |
|  14  | 14/16 = .875  |
|  16  | 16/16 = 1     |
|  18  | 18/16 = 1.125 |
|  20  | 20/16 = 1.25  |
|  24  | 24/16 = 1.5   |
|  30  | 30/16 = 1.875 |
|  36  | 36/16 = 2.25  |
|  42  | 42/16 = 2.625 |
|  48  | 48/16 = 3     |
------------------------- 

1. Install postcss-px2rem and px2rem-loader, recommend cnpm

npm install postcss-px2rem px2rem-loader --save

2. Create a new rem.js proportional adaptation file under the utils directory in the root directory src, and copy the following code directly

const baseSize = 16
// 设置 rem 函数
function setRem () {
  // 当前页面宽度相对于 1920宽的缩放比例,可根据自己需要修改。
  const scale = document.documentElement.clientWidth / 1920
  // 设置页面根节点字体大小(“Math.min(scale, 2)” 指最高放大比例为2,可根据实际业务需求调整)
  document.documentElement.style.fontSize = baseSize * Math.min(scale, 2) + 'px'
}
// 初始化
setRem()
// 改变窗口大小时重新设置 rem
window.onresize = function () {
  setRem()
}

3. Introduce the adaptation file in main.js

import './utils/rem'

4. Configure the plug-in in vue.config.js, copy the code and paste it into it

// 引入等比适配插件
const px2rem = require('postcss-px2rem')

// 配置基本大小
const postcss = px2rem({
  // 基准大小 baseSize,需要和rem.js中相同
  remUnit: 16
})

// 使用等比适配插件
module.exports = {
  lintOnSave: true,
  css: {
    loaderOptions: {
      postcss: {
        plugins: [
          postcss
        ]
      }
    }
  }
}

2. The overall layout adapts to the screen layout as the resolution changes

1. Install lib-flexible in the project

npm install lib-flexible --save

2. Introduce lib-flexible in the project's entry main.js file

import 'lib-flexible'

The overall layout may not be suitable, please focus on the above (one) article

**

The last thing to note is that it cannot be written in the inline style, that is, the style of the div in the body, otherwise lib-flexible and postcss-px2rem-exclude will not take effect, and the layout will be messy. If there are articles, remember to pay attention and pay attention. Please correct me if I am wrong, thank you! ! !

**

Guess you like

Origin blog.csdn.net/m0_49714202/article/details/122943765#comments_24421316