@if を使って条件分岐をする

Sass
1
// 汎用的なclassを使うかどうか
2
$generalStyle: true;
3
4
@if $generalStyle {
5
.text-accent {
6
color: red;
7
}
8
.text-link {
9
color: blue;
10
}
11
}
Sass
1
$getStyle: 0;
2
3
@mixin style {
4
@if $getStyle == 1 {
5
margin: 0 0 30px;
6
padding: 15px;
7
background: #eee;
8
}
9
@else if $getStyle == 2 {
10
margin: 0 10px 15px;
11
padding: 20px 15px;
12
border: 2px solid #333;
13
}
14
@else {
15
margin: 0 0 10px;
16
}
17
}
18
19
.box {
20
@include style;
21
}
CSS
1
.box {
2
margin: 0 0 10px;
3
}
CSS
1
.box {
2
margin: 0 10px 15px;
3
padding: 20px 15px;
4
border: 2px solid #333;
5
}

@for で繰り返し処理を行う

Sass
1
@for $value from 1 through 3 {
2
.throughSample_#{$value} {
3
margin-bottom: 1px * $value;
4
}
5
}
6
7
@for $value from 1 to 3 {
8
.toSample_#{$value} {
9
margin-bottom: 1px * $value;
10
}
11
}
CSS
1
.throughSample_1 {
2
margin-bottom: 1px;
3
}
4
5
.throughSample_2 {
6
margin-bottom: 2px;
7
}
8
9
.throughSample_3 {
10
margin-bottom: 3px;
11
}
12
13
.toSample_1 {
14
margin-bottom: 1px;
15
}
16
17
.toSample_2 {
18
margin-bottom: 2px;
19
}
Sass
1
@for $value from 1 through 2 {
2
.mt_#{$value * 10} {
3
margin-top: 10px * $value;
4
}
5
.mb_#{$value * 10} {
6
margin-bottom: 10px * $value;
7
}
8
}
CSS
1
.mt_10 {
2
margin-top: 10px;
3
}
4
5
.mb_10 {
6
margin-bottom: 10px;
7
}
8
9
.mt_20 {
10
margin-top: 20px;
11
}
12
13
.mb_20 {
14
margin-bottom: 20px;
15
}

@while でより柔軟な繰り返し処理を行う

Sass
1
$value: 20;
2
@while $value > 0 {
3
.mt_#{$value} {
4
margin-top: #{$value}px
5
}
6
.mb_#{$value} {
7
margin-bottom: #{$value}px
8
}
9
$value: $value - 10;
10
}
Sass
1
$index: 300;
2
@while $index > 200 {
3
.box_#{$index} {
4
width: 2px * $index;
5
}
6
$index: $index - 32;
7
}
CSS
1
.box_300 {
2
width: 600px;
3
}
4
5
.box_268 {
6
width: 536px;
7
}
8
9
.box_236 {
10
width: 472px;
11
}
12
13
.box_204 {
14
width: 408px;
15
}

@each で配列の要素に対して処理を実行する

CSS
1
.body-top {
2
background-image: url(../img/bg_top.png);
3
}
4
.body-about {
5
background-image: url(../img/bg_about.png);
6
}
7
.body-company {
8
background-image: url(../img/bg_company.png);
9
}
10
.body-contact {
11
background-image: url(../img/bg_contact.png);
12
}
Sass
1
$nameList: top, about, company, contact;
2
3
@each $name in $nameList {
4
.body-#{$name} {
5
background-image: url(../img/bg_#{$name}.png);
6
}
7
}

サンプルコード一覧へ

Amazonで購入する