一、在index.html头部加入手机端自适应meta
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
二、vue项目中使用postcss-pxtorem
- 安装插件
npm install postcss postcss-pxtorem --save-dev
- 插件的基本配置
根目录下创建postcss.config.js文件
export default {plugins: {'postcss-pxtorem': {rootValue: 1, unitPrecision: 5, propList: ['*'], selectorBlackList: ['ignore-'], minPixelValue: 2, replace: true, }}
}
- 自定义配置rem基数
app.vue
<script setup>
import { RouterView } from 'vue-router'
import { onMounted, onBeforeUnmount } from 'vue'
const resize = () => {const deviceWidth = document.documentElement.clientWidthdocument.documentElement.style.fontSize = deviceWidth / 375 + 'px'
}onMounted(() => {resize()window.addEventListener('resize', resize)
})
onBeforeUnmount(() => {window.removeEventListener('resize', resize)
})</script><template><RouterView />
</template><style scoped>
header {line-height: 1.5;max-height: 100vh;
}.logo {display: block;margin: 0 auto 2rem;
}nav {width: 100%;font-size: 12px;text-align: center;margin-top: 2rem;
}nav a.router-link-exact-active {color: var(--color-text);
}nav a.router-link-exact-active:hover {background-color: transparent;
}nav a {display: inline-block;padding: 0 1rem;border-left: 1px solid var(--color-border);
}nav a:first-of-type {border: 0;
}@media (min-width: 1024px) {header {display: flex;place-items: center;padding-right: calc(var(--section-gap) / 2);}.logo {margin: 0 2rem 0 0;}header .wrapper {display: flex;place-items: flex-start;flex-wrap: wrap;}nav {text-align: left;margin-left: -1rem;font-size: 1rem;padding: 1rem 0;margin-top: 1rem;}
}
</style>
- 无法将内联样式和js中css的px转成rem