Install dependencies
Recently, I encountered adaptation problems when WRITING mobile terminal projects. In addition to handwriting REM, third-party tools can be well solved and development efficiency can be greatly improved. Here is a record
Use rem units for adaptation. The following two tools are recommended:
- Postcss – Pxtorem is a postCSS plugin for converting PX units to REM units
- Lib-flexible Specifies the REM reference value
npm install postcss postcss-pxtorem --save-dev
npm i -S amfe-flexible
configure
- Create a new one in the root directory
postcss.config.js
Write the following code
module.exports = {
plugins: {
Postcss-pxtorem plugin version requires >= 5.0.0
'postcss-pxtorem': {
rootValue: 75.// Root element font size (1rem value), assuming the design size is 750
propList: [The '*'],}}};Copy the code
- Import file in the entry
amfe-flexible
test
We use vue-CLI to create a project, take out the unwanted files and write the following code in app.vue
<template>
<div id="app">
<div class="box">Rem mobile adaptation</div>
</div>
</template>
<script>
export default {
name: 'App',}</script>
<style>
.box {
height: 75px;
font-size: 20px;
line-height: 75px;
background: pink;
}
</style>
Copy the code
Open the browser and you can see that the PX style of our department has been automatically converted to REM, and the root font size will be automatically set when switching between different devices. It should be noted that the inline style will not be converted
If the runtime error is postCSS8, reduce the postCSS-pxtorem version to 5.1.1
ADAPTS to the Vant third-party UI framework
module.exports = {
plugins: {
Postcss-pxtorem plugin version requires >= 5.0.0
'postcss-pxtorem': {
rootValue({ file }) {
// Vant is written based on 375px
return file.indexOf('vant')! = = -1 ? 37.5 : 75 // (Fill in 75 here according to the size of the actual design draft)
},
propList: [The '*'],}}};Copy the code
Close test to use