一. 使用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>

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

2298

被折叠的 条评论
为什么被折叠?



