关于sass:sassscss-对比css的优势

1:@import的区别

二者的性能都是在css文件中 导入其余css款式文件

CSS: css中的@import是为了开发者能将css分解成更小的局部,它的引入会间接发动一个HTTP的申请。
SCSS预编译: scss的@import则更加像咱们应用的import等模块化的货色,它是间接将代码蕴含进指标SCSS文件,而不会产生额定的http申请。

2:应用变量

// 申明
$blue: #3190e8; 
$highlight-color: #F90;
// 应用:
$nav-color: #F90;
nav {
  $width: 100px;
  width: $width;
  color: $nav-color;
}

// 编译后
nav {
  width: 100px;
  color: #F90;
}

3: 混合器

如果你的整个网站中有几处小小的款式相似(例如统一的色彩和字体),那么应用变量来对立解决这种状况是十分不错的抉择。然而当你的款式变得越来越简单,你须要大段大段的重用款式的代码,独立的变量就没方法应酬这种状况了。你能够通过sass的混合器实现大段款式的重用。

混合器应用@mixin定义,这个标识符给 一大段款式赋予一个名字。这样你就能够援用这个名字 重用这些款式
例子A:


// mixin.scss文件
@mixin cl {
     display: center;
     align-items: center;
     justify-content: center;
}

// 而后就能够在你的样式表用@include 来应用这个混合器。
<style lang="scss" scoped>
@import 'src/style/mixin';
 .button{
     @include cl;
 }
 
 //scss最终生成
 .button{
      display: center;
      align-items: center;
      justify-content: center;
}
</style>

例子B: 给混合器传参数

// 字体大小,色彩
@mixin sc($size, $color){
    font-size: $size;
    color: $color;
}
@mixin wh($width, $height){
    width: $width;
    height: $height;
}


.list{
     @include sc(0.5rem, #999);
     @include wh(100px, 100px);
}    

例子C: 混合器默认参数

@mixin fg ($type: spance-between){
     display: flex;
     justify-content: $type;
}     

4: 继承@extend
@extend指令通知sass一个选择器的款式从另一个选择器继承。
应用场景:
咱们创立了一个根本的按钮款式 button-basic, 接着咱们定义了两个按钮 button-report和 button-submit,他们都继承了button-basic, 他们次要的区别是 背景色彩和字体色彩,其余款式都是一样的。
应用了@extend后 咱们在html标签中就不须要 class=”.button-basic .button-submit”,只须要设置class=”.button-submit”类 就能够了
@extend很好的体现了代码的复用

.button-basic{
    font-size: 16px;
    border: none;
    padding: 10px 15px;
    text-align: center;
    line-height: 40px;
    cursor: pointer;
 }
 
.button-report{
    @extend .button-basic;
    background-color: red;
}
.button-submit{
    @extend .button-basic;
    background-color: blue;
    color: white;
} 
 
// 将以上代码转换为 CSS 代码,如下所示:
.button-basic, .button-report, .button-submit {
    border: none;
    padding: 15px 30px;
    text-align: center;
    font-size: 16px;
    cursor: pointer;
} 
.button-report  {
    background-color: red;
}

.button-submit  {
    background-color: blue;
    color: white;
} 

小结:

  1. 变量是sass提供的最根本的工具,通过变量能够让css值变得可重用。
  2. 同样根底的是嵌套机制,缩小反复编写同样的选择器,能够让构造更加清晰。
  3. sass提供了非凡的父选择器标识符&,通过他能够结构出更高效的嵌套。
  4. 通过这些关系能够放弃你的代码整洁性和 可维护性。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理