记录一下,vue的移动端适配:vue-cli4 + postcss + postcss-cli + postcss-pxtorem + amfe-flexible ,实现设计稿按 一比一 设置css大小,并实现移动端适配,样式自动添加浏览器前缀。
新建vue项目(这里用的是vue-cli4):
vue create my-demo
安装 amfe-flexible:
npm i -S amfe-flexible
main.js 引入 amfe-flexible
import 'amfe-flexible';
效果:实现根字体大小自动设置
加一点点样式用来测试(里面的图片自己随便找几个用上,不然会报错):
<template>
<div id="app">
<section class="header">
<span class="navBtn"></span>
<div class="serchWrap">
<span>路飞商城</span>
<div class="serch showIcon">
</div>
</div>
<span class="userIcon"></span>
</section>
</div>
</template>
<script>
export default {
name: "App",
components: {
},
};
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.header {
width: 100%;
height: 37px;
display: flex;
justify-content: space-around;
align-items: center;
}
.navBtn {
display: inline-block;
height: 32px;
width: 32px;
background-size: 100% 100%;
background-image: url(./assets/img/navBtn.png);
}
.serchWrap {
height: 32px;
width: 279px;
}
.serchWrap span {
width: 107px;
height: 30px;
float: left;
font-size: 18px;
border: solid 1px #1296db;
border-radius: 30px 0 0 30px;
text-align: center;
line-height: 30px;
font-weight: 500;
color: #1296db;
}
.serchWrap .serch {
float: left;
width: 168px;
height: 30px;
border: solid 1px #1296db;
border-radius: 0 30px 30px 0;
border-left: none;
font-size: 14px;
text-indent: 14px;
color: #1296db;
line-height: 30px;
}
.serchWrap .serch input {
float: left;
width: 168px;
height: 30px;
border: solid 1px #1296db;
border-radius: 0 30px 30px 0;
border-left: none;
overflow: hidden;
outline: none;
text-indent: 14px;
}
.showIcon {
position: relative;
}
.showIcon:before {
content: "";
display: block;
position: absolute;
background-size: 80% 80%;
background-position: 50% 50%;
background-repeat: no-repeat;
background-image: url(./assets/img/serch.png);
width: 25px;
height: 25px;
top: 50%;
transform: translateY(-50%);
left: 8px;
opacity: 0.7;
}
.userIcon {
width: 30px;
height: 30px;
background-size: 100% 100%;
background-image: url(./assets/img/userIcon.png);
}
</style>
效果:
接着搞:安装 postcss postcss-pxtorem
npm i postcss postcss-pxtorem@5 -S
这里我试了装 postcss-pxrorem 最新版 6.0+ 报错了,。装回 5.0+ ,ojbk
vue-cli3 + 需要自己创建一个 vue.congif.js 文件
module.exports = {
css: {
loaderOptions: {
postcss: {
plugins: [ require('postcss-pxtorem')({
rootValue: 37.5, // 设计稿 375px
propList: ['*']
})]
}
}
}
}
效果:IDE 按设计稿尺寸配置 -> 运行后 px 转成 rem -> 浏览器 rem 转成 px 渲染
利用 autoprefixer 配置样式前缀
npm i autoprefixer@9 -s
在postcss.config.js 中添加 autoprefixer 配置
module.exports = {
plugins: {
'autoprefixer': {
overrideBrowserslist: [
"> 1%",
"last 3 versions",
"not ie <= 8",
"chrome >= 14",
"safari >= 3",
"ios >= 8",
"android >= 4.0"
]
},
'postcss-pxtorem': {
rootValue: 37.5,
propList: ['*'],
selectorBlackList: ['.norem']
}
}
}