由于
viewport单位得到众多浏览器的兼容,lib-flexible这个过渡方案已经可以放弃使用,不管是现在的版本还是以前的版本,都存有一定的问题。建议大家开始使用viewport来替代此方案。vw的兼容方案可以参阅《如何在Vue项目中使用vw实现移动端适配》一文。
之前一直没有尝试使用 vw 进行移动端适配,这次希望在毕设项目中运用,记录一番步骤,具体的插件用途可查阅参考文章~
安装 PostCSS 插件
1 | npm i postcss-aspect-ratio-mini postcss-px-to-viewport postcss-write-svg postcss-cssnext postcss-viewport-units cssnano --S |
配置插件
在.postcssrc.js文件对新安装的PostCSS插件进行配置:
1 | // https://github.com/michael-ciniawsky/postcss-load-config |
特别声明:由于
cssnext和cssnano都具有autoprefixer,事实上只需要一个,所以把默认的autoprefixer删除掉,然后把cssnano中的autoprefixer设置为false。
特别声明:
由于
cssnext和cssnano都具有autoprefixer,事实上只需要一个,所以把默认的autoprefixer删除掉,然后把cssnano中的autoprefixer设置为falsepostcss-viewport-units修改 content ,并不能很好的兼容,会出现以下警告:1
(Emitted value instead of an instance of Error) postcss-viewport-units: ... a:after' already has a 'content' property, give up to overwrite it.
解决办法: 如果没有版本需求,可以考虑去掉; 或者进行过滤,具体如下:
1
2
3"postcss-viewport-units": {
filterRule: rule => rule.nodes.findIndex(i => i.prop === 'content') === -1,
},
使用
在不想要把 px 转换为 vw 的时候,首先在对应的元素(html)中添加配置中指定的类名 .ignore 或 .hairlines (.hairlines 一般用于设置 border-width:0.5px 的元素中):
1 | <div class="box ignore"></div> |
写 CSS 时
1 | .ignore { |
编译出来的 CSS
1 | .box { |
上面解决了px到vw的转换计算。那么在哪些地方可以使用vw来适配我们的页面。根据相关的测试:
- 容器适配,可以使用
vw - 文本的适配,可以使用
vw - 大于
1px的边框、圆角、阴影都可以使用vw - 内距和外距,可以使用
vw