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>
按照上面的公式, 375宽度的html的字体大小是37.5px; top类为15px的font-size转换为rem的就是15 / 37.5 = 0.4rem

750宽度的html的字体大小是75px,top类为15px的font-size转换为rem的还是15 / 37.5 = 0.4rem

为什么750px宽度的屏幕的rem值没有变化呢?
(1) rem是相对单位;
rem单位是相对于HTML标签的字号计算结果;[网页的根标签是:html标签;html字号也叫根字号,根标签字号。]
1rem = 1HTML字号大小。
(2) px转rem计算:
rem(css属性) = px(css属性) / px(html或者body[优先找html]的fontSize);
反过来rem转化为px就是:
px(css属性) = rem的数值 * html的fontSize数值;
如果html标签的font-size是16px,那么1rem就是16px, 而0.4rem就是0.4*16 = 6.4px。
如果html标签的font-size是20px,那么1rem就是16px, 而0.4rem就是0.4*20 = 8px。
如果html标签的font-size是37.5px,那么1rem就是37.5px, 而0.4rem就是0.4*37.5 = 15px。
如果html标签的font-size是75px,那么1rem就是75px, 而0.4rem就是0.4*75 = 30px。
从计算可知: 750px是375px的2倍,所以计算结果是无误的.
虽然是vue3项目的示例,但原理都差不多, react项目根据它的代码要求改改应该就能用了.
- @function px2rem($px) {
- $item: 37.5px;
- @return $px/$item+rem;
- }
- //使用方式
- div {
- width: px2rem(100px);
- }
sass/scss写移动端自适应样式,将px转化为rem-CSDN博客
- <style scoped lang="stylus">
- px2rem(designpx)
- $rem = 37.5px;
- return (designpx / $rem)rem
- </style>
rem自适应原理--vue如何自己利用stylus写rem自适应移动端_stylus 获取屏幕宽度-CSDN博客
Less 的函数全是内置的并不能自定义,所以只能使用混合mixin来实现转换逻辑的复用。
- .pxToRem (@px, @attr: width) {
- @rem: (@px / 37.5);
- @{attr}: ~"@{rem}rem";
- }
-
-
- // Less
- .box {
- .pxToVW(75);
- .pxToVW(150, height);
- }
-
- // CSS
- .box {
- width: 2rem;
- height: 4rem;
- }
上述几种方法期望的37.5px的html的值都是通过把容器宽度 / 10 + px单位获取的
1. 页面渲染后将html的字体大小设置为容器宽度/10, 加上px单位
2. resize事件中也重写: 将html的字体大小设置为容器宽度/10, 加上px单位
html {
font-size: 10vw;
}
修改postcss-loader如下:
{
loader: 'postcss-loader',
options: {
plugins: [
require('autoprefixer', {
overrideBrowserslist: ['Android >= 4.0', 'iOS >= 7'],
}),
require('postcss-pxtorem')({
// 根节点的 fontSize 值
rootValue: 37.5, // (Number | Function) 表示根元素字体大小或根据input参数返回根元素字体大小
unitPrecision: 5, // (数字)允许 REM 单位增长到的十进制数字
propList: ['*'], // 可以从 px 更改为 rem 的属性 使用通配符*启用所有属性
// selectorBlackList: [],// (数组)要忽略并保留为 px 的选择器。
// replace: true, // 替换包含 rems 的规则,而不是添加回退。
// mediaQuery: true, // 允许在媒体查询中转换 px
// minPixelValue: 0, // 最小的转化单位
exclude: "/node_modules|floder_name/i" // 要忽略并保留为 px 的文件路径
}),
]
}
},
- const path = require('path')
- const webpack = require('webpack')
- const webpackCommonConf = require('./webpack.common.js')
- const { smart } = require('webpack-merge')
- const { srcPath, distPath } = require('./paths.js')
- const HotModuleReplacementPlugin = require('webpack/lib/HotModuleReplacementPlugin')
- const DllReferencePlugin = require('webpack/lib/DllReferencePlugin')
-
- module.exports = smart(webpackCommonConf, {
- mode: 'development',
- module: {
- rules: [
- // 直接引入图片 url
- {
- test: /\.(png|jpg|jpeg|gif)$/,
- use: 'file-loader'
- },
- {
- test: /\.css$/,
- // loader 的执行顺序是:从后往前
- loader: ['style-loader', {
- loader: "css-loader",
- options: {
- sourceMap: true,
- modules: true,
- },
- }, {
- loader: 'postcss-loader',
- },] // 加了 postcss
- },
- {
- test: /\.scss$/,
- // 增加 'less-loader' ,注意顺序
- loader: ['style-loader', {
- loader: "css-loader",
- options: {
- sourceMap: true,
- modules: true,
- }
- },
- {
- loader: 'postcss-loader',
- options: {
- plugins: [
- require('autoprefixer', {
- overrideBrowserslist: ['Android >= 4.0', 'iOS >= 7'],
- }),
- require('postcss-pxtorem')({
- // 根节点的 fontSize 值
- rootValue: 37.5, // (Number | Function) 表示根元素字体大小或根据input参数返回根元素字体大小
- unitPrecision: 5, // (数字)允许 REM 单位增长到的十进制数字
- propList: ['*'], // 可以从 px 更改为 rem 的属性 使用通配符*启用所有属性
- // selectorBlackList: [],// (数组)要忽略并保留为 px 的选择器。
- // replace: true, // 替换包含 rems 的规则,而不是添加回退。
- // mediaQuery: true, // 允许在媒体查询中转换 px
- // minPixelValue: 0, // 最小的转化单位
- exclude: "/node_modules|floder_name/i" // 要忽略并保留为 px 的文件路径
- }),
- ]
- }
- },
- {
- loader: "sass-loader",
- }
- ]
- }
- ]
- },
- // 输出source-map, 方便直接调试es6源码
- devtool: 'source-map',
- plugins: [
- new webpack.DefinePlugin({
- // window.ENV = 'development'
- 'process.env': {
- NODE_ENV: JSON.stringify(process.env.NODE_ENV)
- }
- }),
- // 热更新
- new HotModuleReplacementPlugin(),
- new DllReferencePlugin({
- // 描述react动态链接库的文件内容(告知webpack索引的位置)
- manifest: require(path.join(distPath, 'react.manifest.json')),
- }),
- ],
- devServer: {
- hot: true,
- port: 8111,
- progress: true, // 显示打包的进度条
- contentBase: distPath, // 根目录
- open: false, // true:自动打开浏览器
- compress: true, // 启动 gzip 压缩
- // 设置代理
- proxy: {
- '/api': 'http://localhost:8000',
- '/api2': {
- target: 'http://localhost:8111',
- pathRewrite: {
- '/api2': ''
- }
- }
- }
- }
- })
如果取修改webpack配置一直没有成功, 可以就在package.json写:
- "postcss": {
- "plugins": {
- "autoprefixer": {},
- "postcss-pxtorem": {
- "rootValue": 37.5,
- "propList": ["*"],
- "exclude": "/node_modules|floder_name/i"
- }
- }
- }
