使用postcss-pxtorem插件实现px转换rem

文章详细介绍了如何在Vue项目中使用postcss-pxtorem插件将设计稿中的px单位转换为rem,并提供了不使用插件的其他方法,以及给html字体大小赋值的注意事项。还涉及到了webpack配置和不同CSS预处理器的使用技巧。

一. 使用postcss-pxtorem的方法和流程:

1.下载postcss-pxtorem(其他插件按需下载自行配置)并在package.json同级目录下新建postcss.config.js文件:

export const defaultHtmlFontSize = 37.5
export default {
  plugins: {
    autoprefixer: {
      overrideBrowserslist: ['Android >= 4.0', 'iOS >= 7'],
    },
    'postcss-pxtorem': {
      // 根节点的 fontSize 值
      rootValue: defaultHtmlFontSize,
      propList: ['*'],
      selectorBlackList: [':root'],
    },
  },
}

2.在utils目录下新建rem.ts文件

import {defaultHtmlFontSize} from '../../postcss.config'

// 设置 rem 函数
export const setRem = () => {
    // 375 默认字体大小37.5px; 375px = 10rem(px的数值/37.5)
    const designScreenWidth = 375;
    
    const scale = designScreenWidth / defaultHtmlFontSize
    const htmlWidth = document.documentElement.clientWidth || document.body.clientWidth
    // 得到html的Dom元素
    const htmlDom = document.getElementsByTagName('html')[0]
    // 设置根元素字体大小
    htmlDom.style.fontSize = htmlWidth / scale + 'px'
  }

export const initRem = () => {
    // 初始化
    setRem()
    // 改变窗口大小时重新设置 rem
    window.onresize = function() {
        setRem()
    }
}

3.在main.ts文件调用initRem方法:

import { createApp } from 'vue'
import {createPinia} from 'pinia'
import App from './App.vue'
import router from './router'
import { initRem } from './utils/rem'

const app = createApp(App)
app.use(createPinia());
app.use(router)


// const rootValue = 37.5
// const rootWidth = 375
// const deviceWidth = document.documentElement.clientWidth; // 用户的设备屏幕宽度
// document.documentElement.style.fontSize = (deviceWidth * rootValue / rootWidth) + 'px';
initRem();

app.mount('#app')

设计图要使用375px宽度的,然后直接写px就行了,如果是750的设计图,就/2之后的值,比如border在750的设计图是2px的,在代码中就要写成1px

使用示例:

<style lang="scss" scoped>
.home-top {
    background: linear-gradient(to right, rgb(53, 200, 250), rgb(31, 175, 243));
    color: white;

    .top {
        display: flex;
        align-items: center;
        padding: 10px 10px 0 10px;
        line-height: 15px;
        font-size: 15px;
        font-weight: bold;
    }
}
</style>
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值