Sassの勉強 #10 関数一覧(Ver.3.4) と自作関数
Sassに用意されている関数一覧
Sassのネイティブ関数一覧は下記リファレンスで確認できます。
色関連の関数
RGB関連の関数
- rgb($red, $green, $blue)
赤、緑、青の値から色を作成する。 - rgba($red, $green, $blue, $alpha)
赤、緑、青、およびアルファ値から、色を作成する。 - red($color)
RGBの赤(R値)を返す。 - green($color)
RGBの緑(G値)を返す。 - blue($color)
RGBの青(B値)を返す。 - mix($color1, $color2, [$weight])
2つの色を混ぜて中間色を作成する。
HSL関連の関数
- hsl($hue, $saturation, $lightness)
色相、彩度、輝度の値から色を作成する。 - hsla($hue, $saturation, $lightness, $alpha)
色相、彩度、輝度、およびアルファ値から、色を作成する。 - hue($color)
HSLの色相(hue値)を返す。 - saturation($color)
HSLの彩度(saturation値)を返す。 - lightness($color)
HSLの輝度(lightness値)を返す。 - adjust-hue($color, $degrees)
色相を変更する。 - lighten($color, $amount)
明度を上げる。(明るくする) - darken($color, $amount)
明度を下げる。(暗くする) - saturate($color, $amount)
彩度を上げる。 - desaturate($color, $amount)
彩度を下げる。 - grayscale($color)
グレースケールに変換する。 - complement($color)
補色を返す。 - invert($color)
色を反転させて返す。
透明度関連の関数
- alpha($color) / opacity($color)
透明度を取得する。 - rgba($color, $alpha)
透明度を変更する。 - opacify($color, $amount) / fade-in($color, $amount)
より不透明にする。 - transparentize($color, $amount) / fade-out($color, $amount)
より透明にする。
その他の色に関連する関数
- adjust-color($color, [$red], [$green], [$blue], [$hue], [$saturation], [$lightness], [$alpha])
あらゆる色の値を一気に調整する。 - scale-color($color, [$red], [$green], [$blue], [$saturation], [$lightness], [$alpha])
流動的に色を変更する。(Fluidly scales one or more properties of a color.←訳せない私) - change-color($color, [$red], [$green], [$blue], [$hue], [$saturation], [$lightness], [$alpha])
指定した色の値を変更。 - ie-hex-str($color)
IEフィルタ(filterプロパティ)に実装されているフォーマットに変換する。
文字列関連の関数
- unquote($string)
文字列からクォーテーションを取り除く。
unquote("foo") => foo
unquote(foo) => foo - quote($string)
文字列にクォーテーションを加える。
quote("foo") => "foo"
quote(foo) => "foo" - str-length($string)
文字列の長さを返す。
str-length("foo") => 3 - str-insert($string, $insert, $index)
$stringの$indexの位置へ$insertを挿入する。
str-insert("abcd", "X", 1) => "Xabcd"
str-insert("abcd", "X", 4) => "abcXd" - str-index($string, $substring)
$stringの中で$substringが何番目(何文字目)かを返す。
str-index(abcd, a) => 1
str-index(abcd, ab) => 1
str-index(abcd, X) => null
str-index(abcd, c) => 3 - str-slice($string, $start-at, [$end-at])
$stringの中で指定した箇所から(指定した箇所まで)の抜粋したものを返す。
str-slice("abcd", 2, 3) => "bc"
str-slice("abcd", 2) => "bcd"
str-slice("abcd", -3, -2) => "bc"
str-slice("abcd", 2, -2) => "bc" - to-upper-case($string)
$stringを大文字に変換する。
to-upper-case(abcd) => ABCD - to-lower-case($string)
$stringを小文字に変換する。
to-lower-case(ABCD) => abcd
数値関連の関数
- percentage($number)
$numberをパーセンテージに変換する。
percentage(0.2) => 20%
percentage(100px / 50px) => 200% - round($number)
$numberの端数を四捨五入してもっとも近い整数にする。
round(10.4px) => 10px
round(10.6px) => 11px - ceil($number)
$numberの端数を切り上げて次のもっとも近い整数にする。
ceil(10.4px) => 11px
ceil(10.6px) => 11px - floor($number)
$numberの端数を切り捨ててもっとも近い整数にする。
floor(10.4px) => 10px
floor(10.6px) => 10px - abs($number)
$numberの絶対値を返す。
abs(10px) => 10px
abs(-10px) => 10px - min($numbers…)
$numbers…の中で最小値を返す。
min(1px, 4px) => 1px
min(5em, 3em, 4em) => 3em - max($numbers…)
$numbers…の中で最大値を返す。
max(1px, 4px) => 4px
max(5em, 3em, 4em) => 5em - random([$limit])
乱数を返す。
リスト関連の関数
- length($list)
$listの長さ(項目数)を返す。
length(10px) => 1
length(10px 20px 30px) => 3
length((width: 10px, height: 20px)) => 2 - nth($list, $n)
$listの中で$n番目の値を返す。
nth(10px 20px 30px, 1) => 10px
nth((Helvetica, Arial, sans-serif), 3) => sans-serif
nth((width: 10px, length: 20px), 2) => length, 20px - set-nth($list, $n, $value)
$list,の$n番目の値(項目)を$valueに置き換える。
set-nth(10px 20px 30px, 2, -20px) => 10px -20px 30px - join($list1, $list2, [$separator])
$list1と$list2を結合する。
join(10px 20px, 30px 40px) => 10px 20px 30px 40px
join((blue, red), (#abc, #def)) => blue, red, #abc, #def
join(10px, 20px) => 10px 20px
join(10px, 20px, comma) => 10px, 20px
join((blue, red), (#abc, #def), space) => blue red #abc #def - append($list1, $val, [$separator])
$list1の最後に$valを追加する。
append(10px 20px, 30px) => 10px 20px 30px
append((blue, red), green) => blue, red, green
append(10px 20px, 30px 40px) => 10px 20px (30px 40px)
append(10px, 20px, comma) => 10px, 20px
append((blue, red), green, space) => blue red green - zip($lists…)
$lists(複数のリスト)を1つの多次元リストに統合する。
zip(1px 1px 3px, solid dashed solid, red green blue) => 1px solid red, 1px dashed green, 3px solid blue - index($list, $value)
$listの中の$valueの位置を返す。
index(1px solid red, solid) => 2
index(1px solid red, dashed) => null
index((width: 10px, height: 20px), (height 20px)) => 2 - list-separator(#list)
リスト内のセパレーターを返す。
list-separator(1px 2px 3px) => space
list-separator(1px, 2px, 3px) => comma
list-separator(‘foo’) => space
マップ関連の関数
- map-get($map, $key)
$mapの中の$keyの値を返す。
map-get(("foo": 1, "bar": 2), "foo") => 1
map-get(("foo": 1, "bar": 2), "bar") => 2
map-get(("foo": 1, "bar": 2), "baz") => null - map-merge($map1, $map2)
$map1と$map2を結合する。
map-merge(("foo": 1), ("bar": 2)) => ("foo": 1, "bar": 2)
map-merge(("foo": 1, "bar": 2), ("bar": 3)) => ("foo": 1, "bar": 3) - map-remove($map, $keys…)
$mapの中の$keys(キーとそれに対する値)を削除して返す。
map-remove(("foo": 1, "bar": 2), "bar") => ("foo": 1)
map-remove(("foo": 1, "bar": 2, "baz": 3), "bar", "baz") => ("foo": 1)
map-remove(("foo": 1, "bar": 2), "baz") => ("foo": 1, "bar": 2) - map-keys($map)
$mapの中のキーのリスト返す。
map-keys(("foo": 1, "bar": 2)) => "foo", "bar" - map-values($map)
$mapの中の(キーに対する)値のリスト返す。
map-values(("foo": 1, "bar": 2)) => 1, 2
map-values(("foo": 1, "bar": 2, "baz": 1)) => 1, 2, 1 - map-has-key($map, $key)
$mapの中に$keyが含まれるかのどうかの真偽を返す。
map-has-key(("foo": 1, "bar": 2), "foo") => true
map-has-key(("foo": 1, "bar": 2), "baz") => false - keywords($args)
$args(可変長引数)から引数の名前をファンクションやミックスインへリストとして返すやつ?(←よく分かってないから違うかも。まぁでもなんか基本名的にマップ用の何か。)
セレクタ関連の関数
- selector-nest($selectors…)
$selectors…の値をネストされたセレクタとして返す。($selectorsをネストさせる)
selector-nest(".foo", ".bar", ".baz") => .foo .bar .baz
selector-nest(".a .foo", ".b .bar") => .a .foo .b .bar
selector-nest(".foo", "&.bar") => .foo.bar ←「&」を使えば連結セレクタ - selector-append($selectors…)
$selectors…の値ををスペースなしで追加する。 ($selecorsのリスト順に追加)
selector-append(".foo", ".bar", ".baz") => .foo.bar.baz
selector-append(".a .foo", ".b .bar") => "a .foo.b .bar"
selector-append(".foo", "-suffix") => ".foo-suffix" - selector-extend($selector, $extendee, $extender)
$selectorの中を$extenderによって$extendeeを拡張する。(←よくわからない;;)
selector-extend(".a .b", ".b", ".foo .bar") => .a .b, .a .foo .bar, .foo .a .bar - selector-replace($selector, $original, $replacement)
$selectorの$originalを$replacementに置換する。
selector-replace(".foo .bar", ".bar", ".baz") => ".foo .baz"
selector-replace(".foo.bar.baz", ".foo.baz", ".qux") => ".bar.qux" - selector-unify($selector1, $selector2)
$selector1と$selector2を組み合わせたセレクタを返す。(組み合わせを全て返す)
selector-unify(".a", ".b") => .a.b
selector-unify(".a .b", ".x .y") => .a .x .b.y, .x .a .b.y
selector-unify(".a.b", ".b.c") => .a.b.c
selector-unify("#a", "#b") => null - is-superselector($super, $sub)
$superが$subの親要素かどうかの真偽を返す。
is-superselector(".foo", ".foo.bar") => true
is-superselector(".foo.bar", ".foo") => false
is-superselector(".bar", ".foo .bar") => true
is-superselector(".foo .bar", ".bar") => false - simple-selectors($selector)
$selector(連結セレクタ)を分解してシンプルなセレクタを返す。
simple-selectors(".foo.bar") => ".foo", ".bar"
simple-selectors(".foo.bar.baz") => ".foo", ".bar", ".baz" - selector-parse($selector)
$selectorをパースしてセレクタを返す。
selector-parse(".foo .bar, .baz .bang") => (‘.foo’ ‘.bar’, ‘.baz’ ‘.bang’)
内部の値に関する関数
- feature-exists($feature)
現在のSassのランタイム内に$featureが存在するかどうかの真偽を返す。
feature-exists(some-feature-that-exists) => true
feature-exists(what-is-this-i-dont-know) => false - variable-exists($name)
現在のスコープ内、およびグローバルスコープ内に$nameという変数が存在するかどうかの真偽を返す。
$a-false-value: false;
variable-exists(a-false-value) => true
variable-exists(nonexistent) => false - global-variable-exists($name)
$nameというグローバル変数が存在するかどうかの真偽を返す。
$a-false-value: false;
global-variable-exists(a-false-value) => true
.foo {
$some-var: false;
@if global-variable-exists(some-var) { /* false, doesn’t run */ }
} - function-exists($name)
$nameという関数が存在するかどうかの真偽を返す。
function-exists(lighten) => true
@function myfunc { @return "something"; }
function-exists(myfunc) => true - mixin-exists($name)
$nameというミックスインが存在するかどうかの真偽を返す。
mixin-exists(nonexistent) => false
@mixin red-text { color: red; }
mixin-exists(red-text) => true - inspect($value)
$valueの値を文字列で返す。デバッグ用。 - type-of($value)
$valueのデータ型を返す。
type-of(100px) => number
type-of(asdf) => string
type-of("asdf") => string
type-of(true) => bool
type-of(#fff) => color
type-of(blue) => color - unit($number)
$number関連の単位を返す。
unit(100) => ""
unit(100px) => "px"
unit(3em) => "em"
unit(10px * 5em) => "em*px"
unit(10px * 5em / 30cm / 1rem) => "em*px/cm*rem" - unitless($number)
$numberに単位があるかどうかの真偽を返す。(ないのがtrue、あるのがfalse)
unitless(100) => true
unitless(100px) => false - comparable($number1, $number2)
$number1と$number2が足したり引いたり、比較できるかどうかの真偽を返す。
comparable(2px, 1px) => true
comparable(100px, 3em) => false
comparable(10cm, 3mm) => true - call($name, $args…)
動的に関数を呼ぶ関数。(既存のSassの関数と自作関数)
call(rgb, 10, 100, 255) => #0a64ff
call(scale-color, #0a64ff, $lightness: -10%) => #0058ef
$fn: nth;
call($fn, (a b c), 2) => b
その他の関数
- if($condition, $if-true, $if-false)
$conditionがtrueなら$if-trueの値を、$conditionがfalseなら$if-falseの値を返す。
if(true, 1px, 2px) => 1px
if(false, 1px, 2px) => 2px - unique-id()
ユニークな文字列を返す。(値はランダム。9桁の文字列。コンパイル毎に内容は変わる。)
content: unique-id() => content: umtqgncou
@function で自作関数を定義する
Sassには上記のようにたくさんの関数が予め用意されていますが、自分で関数を用意することも出来ます。自作関数の書き方はこんな感じです。
@function 自作関数名($引数){ @return 戻り値; }
自分で関数を定義する際は「@function」で関数の宣言をして、戻り値には「@return」を使用します。
ミックスインと書き方が似ていますが、ミックスインはルールセット毎に使用するのに対して、関数は主に値で使用する、それが用途の違い、とのこと。数値の計算や変換などの処理は関数で処理する。注意点は元からあるネイティブ関数名とバッティングしないように気を付けること。
簡単な使用例
ベースとなるとフォントサイズを変数($baseFontSize)に代入しておいて、関数を通して$baseFontSizeと引数で指定した数値を足したものをプロパティの値にしています。
$baseFontSize: 12; @function setFontSize($value){ @return $baseFontSize + $value + px; } .testFont{ font-size: setFontSize(3); } /* コンパイル後 */ .testFont { font-size: 15px; }
ネイティブ関数との組み合わせ、変数の利用
Sassのネイティブ関数と組み合わせる事も出来ますし、変数を利用する事も可能です。変数を使用する場合、@functionの中で定義した変数はその@function内でしか使えない点に注意。
下記の例では、あるブロックを分割する際に1カラム分の幅がいくらになるかを関数を通して計算しています。
$totalWidth: 1000px; @function columnWidth($value) { $columnWidth: floor($totalWidth / $value); @return $columnWidth; } .testColumn1{ width:columnWidth(7); } .testColumn2{ width:columnWidth(5); } /* コンパイル後 */ .testColumn1 { width: 142px; } .testColumn2 { width: 200px; }
合計の幅を予め変数に代入しておいて、関数の引数($value)でカラム数を指定、「合計の幅/カラム数」で1カラム毎の幅を$columnWidthに代入して返します。また、$columnWidthがいつも割り切れる数になるとは限らないので、ネイティブ関数のfloor()を用いて四捨五入しています。
引数の初期値を指定
引数の初期値を指定しておくことも可能です。引数の初期値はミックスインと同様に「($引数: 初期値)」で指定します。
$totalWidth: 1000px; $defaultColumn: 4; @function columnWidth($value: $defaultColumn) { $columnWidth: floor($totalWidth / $value); @return $columnWidth; } .testColumn3{ width:columnWidth(); } .testColumn4{ width:columnWidth(6); } /* コンパイル後 */ .testColumn3 { width: 250px; } .testColumn4 { width: 166px; }
@debugと@warn
最後に「@debug」と「@warn」のお話。どちらもテストやデバッグに使用するもので、出力されるCSSには何も直接影響はしません。コマンド画面に何かメッセージを出してくれるもので、主にミックスインや今回の関数のテストやデバッグに使用します。
@debugの使い方
「@debug」の書き方は下記のとおりです。
@debug 結果を確認したい変数など
シンプルな例ですが、まずは簡単な方が良いのでscssファイルに次のような記述をしてみます。
// scssファイル @debug 10px + 15px;
すると下記のようなメッセージがコマンド画面(黒いやつ)に出てきます。
scss/test.scss:786 DEBUG: 25px
「ファイル名:行数 DEBUG: 結果」という形でデバッグ結果が表示されます。
上記サンプルではいきなり「@debug」の行を書いていますが、ミックスインや関数の中で値をとりあえず確認したい際なんかに使うのが普通だと思います。自作関数の箇所で書いたサンプルで使ってみると、こんな感じです。
$totalWidth: 1000px; $defaultColumn: 4; @function columnWidth($value: $defaultColumn) { $columnWidth: floor($totalWidth / $value); @debug $columnWidth; @return $columnWidth; } .debugTest{ width:columnWidth(); }
コマンド画面の方を確認してみると、
scss/test.scss:776 DEBUG: 250px
と表示されます。CSS側でも確認してみると、下記のようにちゃんと同じ数字になっています。
.debugTest { width: 250px; }
同じミックスインや関数の中で複数の「@debug」を使用することが出来ますので、上の例では1つの計算しかしていませんが、色んな処理をしていく過程毎に「@debug」を突っ込めば、処理の途中過程の変数の値の変化も確認出来ます。なんか意図したとおりのCSSが出力されない時などに「@debug」を利用して途中過程の変数の中身を確認してみるとよいのではないかと思います。
@warnの使い方
「@warn」を使用すると、エラーが発生した際に任意のエラーメッセージをコマンド画面に表示させる事が出来ます。自作関数から任意のエラーメッセージを出力させたい時なんかに使う、とのこと。書き方はこんな感じ。
@warn “ここにメッセージ”;
自分の頭では警告を出したいケースが思いつかないのでSassの教科書 – 公式サポートサイトのサンプルソースを引用させて頂きます。(詳しい解説はSassの教科書を読むなりなんなりしてください。とりあえず「何か@warnを使えるサンプル」という意味でここに引用します)
$value: 1000px; @function warnTest(){ @if unitless($value) { $value: $value + px; } @else { @warn "#{$value}は駄目!$valueに単位は入れないで!"; } @return $value; } .box { width: warnTest(); }
コマンド画面にはこんなエラーメッセージがちゃんと表示されました。
WARNING: 1000pxは駄目!$valueに単位は入れないで!
on line 796 of scss/test.scss
ということで、予め「@warn」を設定しておくと、エラーの際に具体的にどうすればいいのか分かりやすく伝える事が出来るようになります。
※GUIコンパイラ(Koalaなど)をを使用した場合、「@debug」や「@warn」などのコマンド画面に表示するディレクティブが結果を表示しないこともあるそうです。
おわりに
さてさて。Sassの勉強シリーズもこれで一旦終了です(*´ω`*)♪
使いこなせます!とは言い切れないけれども、だいぶ理解は出来たかなと思います。
あとは実務でどう使っていくかですなぁ。一緒に仕事する人がSass使える人だと話早いんですが、私周りでは誰も使っていないという不遇な環境。私が開幕SassでCSS出力しても、その後他の人が出力後のCSSファイルをガシガシ汚していく→Sassの意味あった?ってなるのを想像すると…悲しいな、それw
Sassの勉強 関連記事
- Sassの勉強 #00 もっかい最初からやり直そうSassの巻
- Sassの勉強 #01 Sassとは何か?~環境構築
- Sassの勉強 #02 Sassの基本的な機能「ネスト」
- Sassの勉強 #03 Sassの基本的な機能「変数」
- Sassの勉強 #04 Sassの基本的な機能「演算」
- Sassの勉強 #05 Sassの基本的な機能「@import」
- Sassの勉強 #06 スタイルの継承ができる「@extend」
- Sassの勉強 #07 柔軟なスタイル定義が出来る「@mixin」
- Sassの勉強 #08 制御構文(条件分岐・繰り返し)
- Sassの勉強 #09 @at-root
- Sassの勉強 #10 Sassの勉強 #10 関数一覧(Ver.3.4) と自作関数
この記事へのコメントが1 件あります。