---
# System prepended metadata

title: 冷門但好像有機會用到的CSS

---

# 冷門但好像有機會用到的CSS
## 1. counter - 讓css幫你計數
> 最常見得就是如果我們使用 list 清單，樣式選擇 decimal 十進位，當清單變多的時候數字也會跟著增加，底層貌似就是使用 counter 來做的

counter的用法上類似ul和li的關係，一定要父元素和子元素

``` html
    <div class="wrapper">
        <span>西瓜</span>
        <span>葡萄</span>
        <span>草莓</span>
    </div>
```
在這要先針對父元素設定`counter-reset: num;`，num可以任意替換，代表的是累加的變數名，這個變數默認值為0，如果有需要指定特殊的初始值，可以加上第二個參數`counter-reset: num 3;`。

然後在span::before加上`counter-increment: num;`，這一段是進行累加的動作，默認是每次加1，同上，如果想指令累加的值可以給第二個參數`counter-increment: num 2;`

顯示的話就是用`content: counter(num)`，默認list-style-type是decimal，這邊也可透過第二個參數調整`content: counter(num, lower-alhpa)`

以下為範例
#### 範例1
html: 
``` html
<div class="wrapper">
    <div class="item">西瓜</div>
    <div class="item">葡萄</div>
    <div class="item">草莓</div>
</div>
```

css:
``` css
.wrapper {
  counter-reset: num;
}

.item::before {
  counter-increment: num;
  content: counter(num) ". ";
}
```

result:
![image](https://hackmd.io/_uploads/BkKNpF0Ia.png)

#### 範例2
html: 
``` html
<div class="wrapper">
    <div class="item">西瓜</div>
    <div class="item">葡萄</div>
    <div class="item">草莓</div>
</div>
```

css:
``` css
.wrapper {
  counter-reset: num 3;
}

.item::before {
  counter-increment: num 2;
  content: counter(num, lower-alpha) ". ";
}
```

result:
![image](https://hackmd.io/_uploads/H1yi6tRLT.png)


### 進階用法1
counter-reset可以同時定義多個variable，以下為範例

html:
```html
<div>
  <span>板凳</span>
  <span>沙發</span>
  <span>按摩椅</span>
  <i>電視</i>
  <i>冰箱</i>
  <i>烤箱</i>
  <b>小白菜</b>
  <b>青江菜</b>
  <b>高麗菜</b>
</div>
```

css:
```css
span, i, b {
  display: block;
}

div {
  counter-reset: num1 num2 3 num3 5;
}

span::before {
  counter-increment: num1;
  content: counter(num1, upper-alpha) ". ";
}

i::before {
  counter-increment: num2;
  content: counter(num2, lower-alpha) ". ";
}

b::before {
  counter-increment: num3 5;
  content: counter(num3, decimal) ". ";
}
```

result:
![image](https://hackmd.io/_uploads/S166Jc0L6.png)

### 進階用法2
他也可以做到多層次的巢狀結構計數功能，用法上大致類似，但在content的地方要改用`counters`，以下為範例

html:
```html
<div class="ul">
  <div class="li">第一層
    <div class="ul">
      <div class="li">第二層
        <div class="ul">
          <div class="li">第三層</div>
          <div class="li">第三層</div>
          <div class="li">第三層</div>
        </div>
      </div>
      <div class="li">第二層</div>
      <div class="li">第二層</div>
    </div>
  </div>
  <div class="li">第一層
    <div class="ul">
      <div class="li">第二層</div>
      <div class="li">第二層</div>
    </div>
  </div>
</div>
```

css:
```css
.ul {
  counter-reset: num;
}

.li {
  margin-left: 1.5rem;
}

.li::before {
  counter-increment: num;
  content: counters(num, '.') " ";
}
```

result:
![image](https://hackmd.io/_uploads/SJyt-9CIT.png)

<br><br>

> 資料參考來源
> https://www.oxxostudio.tw/articles/201706/pseudo-element-2.html