Writing similar classes with minor variations, like utility classes, can be a pain to write and update. Sometimes just a single character is the only difference between classes and updating the defining parameter means we need to change it for every class name and value. We can write a class one time and the @for directive can write all the minor variations for us. If the similar classes need to be updated, with the help of the @for directive, they only need to be updated once. In this lesson we learn how to leverage the power of the SCSS @for control directive to relieve the pain.

Basic @for-to loop in SCSS:

// doesn't include 10
@for $i from 1 to 10 {
.order {
order: $i;
}
}

output:

.order {
order:; } .order {
order:; }
...
.order {
order:; }

@for-through:

// includes 5
@for $x from 1 through 5 {
.level {
z-index: $x;
}
}

output:

.level {
z-index:; } ... .level {
z-index:; }

@for with 'if' condition:

@for $i from 0 through 10 {
$value: .5 * $i;
$has-decimal: floor($value) != $value;
$class-name: if(
$has-decimal,
#{$value - 0.5}pt5, // if true
$value // if false
); .mt-#{$class-name} {
margin-top: #{$value}rem;
}
}

output:

.mt-0 {
margin-top: 0rem; } .mt-0pt5 {
margin-top: 0.5rem; } .mt-1 {
margin-top: 1rem; } .mt-1pt5 {
margin-top: 1.5rem; } .. .mt-5 {
margin-top: 5rem; }

Using attr selector:

@for $i from 0 through 10 {
$value: .5 * $i; [class~="mt-#{$value}"] {
margin-top: #{$value}rem;
}
}

output:

[class~="mt-0"] {
margin-top: 0rem; } [class~="mt-0.5"] {
margin-top: 0.5rem; } [class~="mt-1"] {
margin-top: 1rem; } .. [class~="mt-5"] {
margin-top: 5rem; }

@for with @mixin

@mixin light-color-class($color, $color-name,$i) {
$color-value: if($i == 0, $color, lighten($color, 5% * $i)); .#{$color-name}#{$i} {
color: $color-value;
}
} @for $i from 0 through 5 {
@include light-color-class(red, 'passion', $i);
@include light-color-class(green, 'natural', $i);
@include light-color-class(blue, 'cool', $i);
}

output:

.passion0 {
color: red; } .natural0 {
color: green; } .cool0 {
color: blue; } .passion1 {
color: #ff1a1a; } .natural1 {
color: #009a00; } .cool1 {
color: #1a1aff; } ...

最新文章

  1. 深入理解PHP内核(三)概览-SAPI概述
  2. jQuery操作列表数据转成Json再输出为html dom树
  3. php部分---面向对象:定义、实例化、构造函数、析构函数;
  4. Redis与Memcached的incr/decr差异对比
  5. Template
  6. URL编码原理解释
  7. android gradle 多渠道打包
  8. drop table xx purge
  9. DDD领域驱动设计初探
  10. Unity 打包总结和资源的优化和处理
  11. Achartengine.jar绘制动态图形一 --饼图
  12. copy&deepcopy
  13. WKWebView强大的新特性
  14. POJ 3189 Steady Cow Assignment 【二分】+【多重匹配】
  15. BZOJ.1535.[POI2005]SZA-Template(KMP DP)
  16. Eclipse设置注释模板和工作空间背景色为豆沙绿
  17. RBAC 继完善代码之后的,再一次完善
  18. 一文读懂Redis持久化
  19. Spark Shuffle原理解析
  20. Tensorflow%20实战Google深度学习框架 4.2.2 自定义损失函数源代码

热门文章

  1. pdnsd 解析原理
  2. shiro session管理
  3. collapse折叠
  4. tooltip两个特殊的属性
  5. 虚拟机上的企业网络管理系统(cisco works 2000安装配置)
  6. 字符设备驱动-----Linux中断处理体系结构
  7. SQLITE数据表主键设置Id自增方法
  8. Redis .Net客户端源码
  9. 洛谷 P2692 覆盖
  10. Arch Linux实体机安装记录