Vant+postcss pxtorem Implementation of Browser Adaptation Function

  • 2021-10-25 06:02:58
  • OfStack

Rem Layout Adaptation
Styles in Vant use px as units by default. If you need rem units, the following two tools are recommended:
postcss-pxtorem is an postcss plug-in for converting units to rem
lib-flexible is used to set the rem reference value
See the last surprise!

1. npm installation


npm install postcss-pxtorem --save

2. Create. postcssrc. js with the following modifications

Note:
1. After the following annotation code is opened, the script will be prompted to report errors. Although I don't know what's the use, annotation is fine.


module.exports = {
 "plugins": {
 	//"postcss-import": {},
  //"postcss-url": {},
  "autoprefixer": {
   browsers: ['Android >= 4.0', 'iOS >= 7']
  },
  "postcss-pxtorem": {
   "rootValue": 32,
   "propList": ["*"]
  }
 }
}

3. New rem. js


const baseSize = 32
//  Settings  rem  Function 
function setRem () {
 //  The current page width is relative to the  750  Wide zoom ratio, which can be modified according to your own needs. 
 const scale = document.documentElement.clientWidth / 750
 //  Set the font size of the page root node 
 document.documentElement.style.fontSize = (baseSize * Math.min(scale, 2)) + 'px'
}
//  Initialization 
setRem()
//  Reset when changing window size  rem
window.onresize = function () {
 setRem()
}

4. Introducing rem. js into main. js


import "./rem.js"

At this point, Vant+postcss-pxtorem browser adaptation is completed.
You can use px directly in the style and automatically convert it to rem.
Wait, don't go yet! ! ! My guest.
Think it's over here? NO, looking down, there is also an rem adaptation that is not based on postcss-pxtorem.
Go straight to the code without saying much.

5. Create a new rem. js and introduce it in main. js


(function (doc, win) {
 var docEl = doc.documentElement
 var resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize'
 var recalc = function () {
  var clientWidth = docEl.clientWidth
  if (!clientWidth) return
  if (parseInt(20 * (clientWidth / 320)) > 35) {
   docEl.style.fontSize = 35 + 'px'
  } else {
   docEl.style.fontSize = 20 * (clientWidth / 320) + 'px'
  }
 }
 if (!doc.addEventListener) return
 win.addEventListener(resizeEvt, recalc, false)
 doc.addEventListener('DOMContentLoaded', recalc, false)
})(document, window)

import "./rem.js"

6. Add a style global variable and use the


//  The current page width is relative to the  750  Wide zoom ratio, which can be modified according to your own needs. 
$rem: (640/750)/40;
body{
	width: $rem * 24rem;
}

Related articles: