第4章 高度な機能を覚えてSassを使いこなそう4-6 関数を使ってさまざまな処理を実行するSample Code
関数の使い方
1@use 'sass:color';2
3.example {4 background: color.scale(#000, $lightness: 30%);5}1@use 'sass:color' as c;2
3.example {4 background: c.scale(#000, $lightness: 30%);5}数値の絶対値を取得する math.abs()
1@use 'sass:math';2
3$space: -100px;4
5.itemA {6 margin-top: $space;7 padding-top: math.abs($space);8}1.itemA {2 margin-top: -100px;3 padding-top: 100px;4}数値の小数点以下を四捨五入する math.round()
1@use 'sass:math';2
3$width: 100%;4
5.boxA {6 width: math.div($width, 6);7}8.boxB {9 width: math.round(math.div($width, 6));10}1.boxA {2 width: 16.6666666667%;3}4
5.boxB {6 width: 17%;7}数値の小数点以下を切り上げる math.ceil() と数値の小数点以下を切り捨てる math.floor()
1@use 'sass:math';2
3$width: 100%;4
5.boxA {6 width: math.div($width, 3);7}8.boxB {9 width: ceil(math.div($width, 3));10}1.boxA {2 width: 33.3333333333%;3}4
5.boxB {6 width: 34%;7}1@use 'sass:math';2
3$width: 100%;4
5.boxA {6 width: math.div($width, 6);7}8.boxB {9 width: floor(math.div($width, 6));10}1.boxA {2 width: 16.6666666667%;3}4
5.boxB {6 width: 16%;7}16進数のRGB値に透明度を指定して、RGBA形式に変換できる rgb()
1.item {2 color: rgb(#6a5468, 0.8);3}1.item {2 color: rgba(106, 84, 104, 0.8);3}1.item {2 color: rgb(red, .15);3}1.item {2 color: rgba(255, 0, 0, 0.15);3}明るい色や暗い色などを簡単に作れる color.scale()
1@use 'sass:color';2
3body {4 color: color.scale(#000, $lightness: 40%);5}1body {2 color: #666666;3}1@use 'sass:color';2
3body {4 color: color.scale(#fff, $lightness: -20%);5}1body {2 color: #cccccc;3}1@use 'sass:color';2
3$c: #555;4
5.boxA {6 color: color.scale($c, $lightness: 20%);7}8.boxB {9 color: color.scale($c, $lightness: -20%);10}1.boxA {2 color: #777777;3}4
5.boxB {6 color: #444444;7}2つのカラーコードの中間色を作れる color.mix()
1@use 'sass:color';2
3body {4 color: color.mix(#000, #fff, 50%);5}1body {2 color: rgb(127.5, 127.5, 127.5);3}1@use 'sass:color';2
3body {4 color: color.mix(rgba(0, 0, 0, .4), #fff, 50%);5}1body {2 color: rgba(204, 204, 204, 0.7);3}1@use 'sass:color';2
3$a: #000;4$b: #fff;5
6.boxA {7 color: color.mix($a, $b, 80%);8}9.boxB {10 color: color.mix($a, $b, 20%);11}1.boxA {2 color: #333333;3}4
5.boxB {6 color: #cccccc;7}リストのN 番目の値を取得できる list.nth()
1@use 'sass:list';2
3$nameList: top, about, company;4
5.item {6 background: url(#{list.nth($nameList, 2)}.png);7}1.item {2 background: url(about.png);3}指定したキーの値を取得する map.get()
1@use 'sass:map';2
3$colors: (4 instagram: #d1006b,5 facebook: #3b5998,6);7
8.sns-facebook {9 color: map.get($colors, facebook);10}1.sns-facebook {2 color: #3b5998;3}
