移动端适配不同分辨率postcss-plugin-px2rem

响应式:**postcss-plugin-px2rem(插件)+postcss.config.js(文件配置)+setRem.js(文件配置)**方案使用

  1. npm i postcss-plugin-px2rem --save 下载安装
  2. 创建文件postcss.config.js并添加如下代码
// 一般postcss建议单独配置在文件postcss.config.js中
// var px2rem = require('postcss-px2rem');
module.exports = {
   plugins: [
       require('autoprefixer')({
           browsers: 'last 2 versions'
       }),
       require('postcss-plugin-px2rem')({
           remUnit: 75
       })
   ]
}
  1. 在vue.config.js中添加如下代码
lintOnSave: true,
    css: {
        loaderOptions: {
            postcss: {
                plugins: [
                    require('postcss-plugin-px2rem')({
                        // rootValue: 100, //换算基数, 默认100  ,这样的话把根标签的字体规定为1rem为50px,这样就可以从设计稿上量出多少个px直接在代码中写多上px了。
                        // unitPrecision: 5, //允许REM单位增长到的十进制数字。
                        //propWhiteList: [],  //默认值是一个空数组,这意味着禁用白名单并启用所有属性。
                        // propBlackList: [], //黑名单
                        exclude: /(node_module)/, //默认false,可以(reg)利用正则表达式排除某些文件夹的方法,例如/(node_module)/ 。如果想把前端UI框架内的px也转换成rem,请把此属性设为默认值
                        // selectorBlackList: [], //要忽略并保留为px的选择器
                        // ignoreIdentifier: false,  //(boolean/string)忽略单个属性的方法,启用ignoreidentifier后,replace将自动设置为true。
                        // replace: true, // (布尔值)替换包含REM的规则,而不是添加回退。
                        mediaQuery: false, //(布尔值)允许在媒体查询中转换px。
                        minPixelValue: 3 //设置要替换的最小像素值(3px会被转rem)。 默认 0
                    }),
                ]
            }
        }
    },
  1. 在src目录下新建 plugins文件夹,文件夹下新建setRem.js文件,代码如下:
/**
 * html根节点设置font-size
 * @param {designwidth} Number 设计稿的宽度
 */
export const setRem = (designwidth) => {
    function fontSizeFun() {
        const fontSize = 100
        const relwidth = document.documentElement.clientWidth
        const relfontSize = fontSize * relwidth / designwidth + 'px'
        document.getElementsByTagName('html')[0].style.fontSize = relfontSize
    }
    fontSizeFun()
    window.onresize = fontSizeFun
}

  1. 在主入口main.js文件下添加代码
import {
    setRem
} from './plugins/setRem.js'
setRem('750')
//setRem('750') 代表设计稿的大小
// ./plugins/setRem.js 代表创建文件时的路径

效果图:在这里插入图片描述
在iPhone设计稿为750下根元素字体大小为50px

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值