3分钟13行代码搭建sass版移动端网格系统

  • 2019 年 12 月 4 日
  • 筆記

本文作者:IMWeb 结一 原文出处:IMWeb社区 未经同意,禁止转载

一般来说,网格系统分为container、row及column三大部分,而container一般是负责内容居中的,这对pc端比较合适,而大移动端是真的不太需要,所以直接砍掉,那么就剩下row和column了。

上代码:

@mixin row() {      width: 100%;      display: flex;  }  @mixin col($num, $total: 1) {      // 如果$total为默认的1,则表示等分的$num分之一      // 否则计算$num/$total      @if $total == 1 {          width: 100% / $num;      } @else {          width: percentage($num / $total);      }  }

如何使用:

.row{      @include row;  }  // col的命名规范为col-占的格子数-总的格子数  .col-1-2{      @include col(2);  }  .col-1-3{      @include col(1, 3);  }  .col-2-3{      @include col(2, 3);  }  .col-1-4{      @include col(4);  }  .col-3-4{      @include col(3, 4);  }  .col-2-5{      @include col(2,5);  }

最后,扩展成一个百搭可控制的网格系统:

@charset "UTF-8";    //-----------------------------------------------------  // grid system  //-----------------------------------------------------    $gridFlex:          false !default;  $gridRowClearfix:   false !default; // 如果采用float,子元素清除浮动使用clearfix或overflow  $gridClass:         false !default;    // row  @mixin row() {      width: 100%;      @if $gridFlex {          display: flex;      } @else if $gridRowClearfix{          @extend %clearfix;      } @else {          overflow: hidden;      }  }    // col  @mixin col($num, $total: 1) {      @if not $gridFlex {          float: left;      }      // 如果$total为默认的1,则表示等分的$num分之一      // 否则计算$num/$total      @if $total == 1 {          width: 100% / $num;      } @else {          width: percentage($num / $total);      }  }    // 是否开启class  @if $gridClass {      .row{          @include row;      }      .col-1-2{          @include col(2);      }      .col-1-3{          @include col(1, 3);      }      .col-2-3{          @include col(2, 3);      }      .col-1-4{          @include col(4);      }      .col-3-4{          @include col(3, 4);      }      .col-1-5{          @include col(5);      }      .col-2-5{          @include col(2, 5);      }      .col-3-5{          @include col(3, 5);      }      .col-4-5{          @include col(4, 5);      }  }