栅格布局源码分析

@whizbz11 2016-07-03 23:01:00发表于 iuap-design/blog

栅格变量的定义

在variables.scss文件中定义了不同容器宽度下栅格系统的几个变量:列数($grid-columns总是12列, 列间隙宽度$grid-gutter-width和以及不同尺寸的屏幕宽度。

$screen-xs-min:              480px;
//@screen-phone:               @screen-xs-min;
// Small screen / tablet
//@screen-sm:                  768px;
$screen-sm-min:              768px;
//@screen-tablet:              @screen-sm-min;
// Medium screen / desktop
//@screen-md:                  992px;
$screen-md-min:              992px;
//@screen-desktop:             @screen-md-min;
// Large screen / wide desktop
//@screen-lg:                  1200px;
$screen-lg-min:              1200px;
//@screen-lg-desktop:          @screen-lg-min;
$screen-xs-max: ($screen-sm-min - 1 );
$screen-sm-max: ($screen-sm-min -  1 );
$screen-md-max: ($screen-lg-min - 1 );
//栅格列数
$grid-columns:              12;
//列间距一半为左右的padding值。
$grid-gutter-width:         30px;

公共mixin的定义

  • container-fixed容器定义
@mixin container-fixed($gutter: $grid-gutter-width) {
  margin-right: auto;
  margin-left: auto;
  padding-left:  floor(($gutter / 2));
  padding-right: ceil(($gutter / 2));
  @include clearfix;
  //&:extend(.clearfix all);
}
  • row定义
    @mixin make-row($gutter: $grid-gutter-width) {
      margin-left:  ceil(($gutter / -2));
      margin-right: floor(($gutter / -2));
      box-sizing: border-box;
      @include clearfix;
    }

布局上,通过容器的负padding-left和每一个列的margin-left来实现的

  • 列的定义
@mixin make-grid($type){
  .u-col-#{$type}-push-0{
    left:auto;
  }

  .u-col-#{$type}-pull-0{
    right:auto;
  }

  @for $i from 1 through $grid-columns {
 //根据列数占总列数的比例定义每列的宽度
    .u-col-#{$type}-#{$i}{
      width:percentage($i/$grid-columns);
    }
 //距离左侧的距离
    .u-col-#{$type}-push-#{$i}{
      left: percentage($i/$grid-columns);
    }
//距离右侧的距离
    .u-col-#{$type}-pull-#{$i}{
      right: percentage($i/$grid-columns);
    }
//左侧margin的距离,使用他实现列排序
    .u-col-#{$type}-offset-#{$i}{
      margin-left:percentage($i/$grid-columns);
    }
  }
// _md 类型是为了兼容 u-col-1 这种类名
  @if $type == md {
    .u-col-push-0{
      left:auto;
    }
    .u-col-pull-0{
      right:auto;
    }
    @for $i from 1 through $grid-columns {
      .u-col-#{$i}{
        width:percentage($i/$grid-columns);
      }
      .u-col-push-#{$i}{
        left: percentage($i/$grid-columns);
      }
      .u-col-pull-#{$i}{
        right: percentage($i/$grid-columns);
      }
      .u-col-offset-#{$i}{
        margin-left:percentage($i/$grid-columns);
      }
    }
  }
}

其中最大的亮点就是用递归模拟了循环,通过循环避免了重复写12次代码。

具体代码

固定宽度的栅格布局

.u-container {
  @include container-fixed();

  @media (min-width: $screen-sm-min) {
    width: $container-sm;
  }
  @media (min-width: $screen-md-min) {
    width: $container-md;
  }
  @media (min-width: $screen-lg-min) {
    width: $container-lg;
  }
}