前端Vue框架在PostCSS怎样使用sass

更新日期: 2021-07-28阅读: 1.3k标签: PostCSS

为什么要使用Postcss

众所周知转换 px 单位的插件有很多,知名的有 postcss-px-to-viewport 和 postcss-pxtorem,前者是将 px 转成 vw,后者是将 px 转成 rem,精简了不常用的配置。将成为vw优先单位使用,以rem作为回退模式。考虑到vw在移动设备的支持度不如rem,这款插件很好的解决了该问题。然后简单的介绍下。


安装指令

 $ npm install @ moohng / postcss-px2vw --save-dev


使用方法

首先创建一个.postcssrc.js文件,然后配置

module.exports = {
  plugins: {
    '@moohng/postcss-px2vw': {}
  }
}

例子: 使用前:

.box {
  border: 1px solid black;
  margin-bottom: 1px;
  font-size: 20px;
  line-height: 30px;
}

使用后:

.box{
  border: 1px solid black;
  margin-bottom: 1px;
  font-size: 0.625rem;
  font-size: 6.25vw;
  line-height: 0.9375rem;
  line-height: 9.375vw;
}


配置方面

viewportWidth:对应设计图的宽度,用于计算 vw。默认 750,指定 0 或 false 时禁用 rootValue:根字体大小,用于计算 rem。默认 75,指定 0 或 false 时禁用 unitPrecision:计算结果的精度,默认 5 minPixelValue:小于等于该值的 px 单位不作处理,默认 1 注意:该插件只会转换 px 单位。rootValue 一般建议设置成 viewportWidth / 10 的大小,将设计图分成10等分。由于浏览器有最小字体限制,如果设置得过小,页面可能跟预期不一致

如果要使用 rem 单位,需要自己通过 js 来动态计算根字体的大小。如果将设计图分成 10 等分计算,那么根字体的大小应该是 window.innerWidth / 10。

这样一个postCss的插件就配置完成了,希望我的总结能给予你的帮助


sass:常用备忘

常用的sass笔记,快速的开发

一、变量

所有变量以$开头

$font_size: 12px;
.container{
    font-size: $font_size;
}

如果变量嵌套在字符串中,需要写在#{}中

$side : left;
.rounded {
    border-#{$side}: 1px solid #000;
}


二、嵌套

层级嵌套

.container{
    display: none;
    .header{
        width: 100%;
    }
}

属性嵌套,注意,border后需要加上冒号:

.container {
    border: {
        width: 1px;
    }
}

可以通过&引用父元素,常用在各种伪类

.link{
    &:hover{ 
        color: green;
    }  
}


三、mixin

简单理解,是可以重用的代码块,通过@include 命令

// mixin
@mixin focus_style {
    outline: none;
}
div {
    @include focus_style; 
}

编译后生成

div {
  outline: none; }
还可指定参数、缺省值

// 参数、缺省值
@mixin the_height($h: 200px) {
        height: $h;
}
.box_default {
        @include the_height;
}
.box_not_default{
        @include the_height(100px);
}

编译后生成

.box_default {
  height: 200px; }

.box_not_default {
  height: 100px; }


四、继承

通过@extend,一个选择器可以继承另一个选择器的样式。例子如下

// 继承
.class1{
        float: left;
}
.class2{
        @extend .class1;
        width: 200px;
}

编译后生成

.class1, .class2 {
  float: left; }

.class2 {
  width: 200px; }
 

五、运算

直接上例子

.container{
        position: relative;
        height: (200px/2);
        width: 100px + 200px;
        left: 50px * 2;
        top: 50px - 10px;
}

编译后生成

.container {
  position: relative;
  height: 100px;
  width: 300px;
  left: 100px;
  top: 40px; }

插入文件

用@import 来插入外部文件

@import "outer.scss";

也可插入普通css文件

@import "outer.css";

自定义函数

通过@function 来自定义函数

@function higher($h){
        @return $h * 2;
}
.container{
        height: higher(100px);
}

编译后输出

.container {
  height: 200px; 
}


链接: https://www.fly63.com/article/detial/10590

内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!