ありと便利かもしれないmixinシリーズです。
今回はたまーに使いたくなる css counter篇。
css counterとは?
css counterとは、ネイティブのcssで使えるカウンタのことです(そのまんま)。
順序付きリストだったり、セクション番号をつけるのによく使います。(存在が忘れられがちなのでよく使いません)便利です。
初期値の設定や、カウンタの増加値の設定などができます。
:before
、:after
擬似要素のcontent
プロパティに入れることでcss カウンタの値を表示できます。
mixin
@mixin resetCounter($name, $int: 0) {
counter-reset: $name $int;
list-style-type: none;
}
@mixin addCounter($name, $before: '', $after: '', $int: 1) {
&:before {
counter-increment: $name $int;
content: "#{$before}"counter($name)"#{$after}";
}
}
@mixin addCounters($name, $split: '.', $before: '', $after: '', $int: 1) {
&:before {
counter-increment: $name $int;
content: "#{$before}"counters($name, $split)"#{$after}";
}
}
$name
: カウンターの名前。カウンターの名前ごとにカウンターが管理されます。必須です。
$before
: 出力される数字の前に付けたい文字列。デフォルトは空文字列。
$after
: 出力される数字の後に付けたい文字列。デフォルトは空文字列。
$int
:
- resetの場合は初期化後のカウンター値。デフォルトは0。(0なら表示は1から)。
- addの場合は加算されるカウンターの値。デフォルトは1。
$split
: addCounters()
で、カウンターの値を接続する文字列。デフォルトは'-'。(例 3-1-2)
使い方
キャプションに章番号つけるときなど。
addCounter()
します。
$counterName: oreoreCounter;
.parent-section {
@include resetCounter($counterName);
h2 {
@include addCounter($counterName, '第', '章');
}
}
使い方その2
入れ子になってるリストに通し番号(1-1-1みたいな)を付けたいときなど。
addCounters()
します。こちらはs
がつきます。
$counterName: listCounter;
ol {
@include resetCounter($counterName);
li {
@include addCounters($counterName, '-');
}
}
表示結果はご自分でお確かめ下さいまし。