移動端適配方案介紹
- 在移動端中,為了設配不同的設備,通常使用rem來做適配。
- rem是通過根元素進行適配的,網頁中的根元素指的是<html>,我們通過設置<html>的字體大小就可以控制 rem 的大小(1rem = 1根元素字體大小)
- 可見,只要我們根據不同屏幕(使用css媒體查詢或js)設定好根元素<html>的字體大小,其他已經使用了rem單位的元素就會自適應顯示相應的尺寸。
- 設計稿一般是按照一種特定設備型號(如iphone6 375px)為基礎且以px單位來定義樣式,為了讓設計稿能夠通用在不同的設備型號中,則存在着從px到rem的繁瑣計算轉化過程,因此需要更加科學的方式來使用rem單位。
- px2rem或postcss-px2rem的原理:將css中px編譯為rem,配合js根據不同手機型號計算出dpr的值,修改<meta>的viewport值和置<html>的font-size。
配置步驟
1. 安裝依賴包
yarn add lib-flexible postcss-px2rem
2. 配置
- 2.1 導出 webpack 配置文件 :
- 命令 :
yarn eject - 需要添加到本地git倉庫 :
git add . 和 git commit -m xxx - 查看配置文件 :
config/webpack.config.js
- 命令 :
- 2.2 修改配置文件
- 引入模塊 :
const px2rem = require('postcss-px2rem') - 添加配置 :
px2rem({ remUnit: 37.5 })
- 引入模塊 :
px2rem({ remUnit: 37.5 }) 的意思就是1rem = 37.5px 這個是根據375px設計稿來的
2.3 改后代碼
{
loader: require.resolve('postcss-loader'),
options: {
ident: 'postcss',
plugins: () => [
require('postcss-flexbugs-fixes'),
require('postcss-preset-env')({
autoprefixer: {
flexbox: 'no-2009'
},
stage: 3
}),
px2rem({ remUnit: 37.5 }), // 添加的代碼
postcssNormalize()
],
sourceMap: isEnvProduction && shouldUseSourceMap
}
}
3. 引入
在 入口文件 index.js 里引入 lib-flexible
import 'lib-flexible'
4. 演示
- 4.1 編寫的代碼樣式
.one {
width: 200px;
height: 200px;
font-size: 50px;
background: pink;
}
4.2 效果1 : 375px寬
4.3 效果2 :
4.4 效果3
淘寶彈性布局方案lib-flexible不兼容ipad和ipad pro的解決方法
<script>
/(iPhone|iPad|iPhone OS|Phone|iPod|iOS)/i.test(navigator.userAgent)&&(head=document.getElementsByTagName('head'),viewport=document.createElement('meta'),viewport.name='viewport',viewport.content='target-densitydpi=device-dpi, width=480px, user-scalable=no',head.length>0&&head[head.length-1].appendChild(viewport));
</script>
