---
url: https://sugarat.top/bigWeb/css/p2.md
---

# 表格斑马纹

## 选择器nth-child

需要用到`nth-child`这个选择器

* 匹配属于其父元素的第 number 个子元素

## 用法

```css
selector:nth-child (number){
    /* 样式 */
}
```

* odd:奇数
* even:偶数

> [W3School介绍:](http://www.w3school.com.cn/cssref/selector_nth-child.asp)

## 示例

![图片](https://img.cdn.sugarat.top/mdImg/MTU4MjExOTgzMDUzMA==582119830530)

```html
 <table id="testTable" border="1" width="20%">
        <thead>
            <tr>
                <th>col1</th>
                <th>col2</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>1</td>
                <td>1</td>
            </tr>
            <tr>
                <td>2</td>
                <td>2</td>
            </tr>
            <tr>
                <td>3</td>
                <td>3</td>
            </tr>
            <tr>
                <td>4</td>
                <td>4</td>
            </tr>
        </tbody>
    </table>
```

```css
#testTable tbody tr:nth-child(odd) {
    /* 匹配奇数行 */
    background-color: white;
    text-align: center;
    color: black;
}

#testTable tbody tr:nth-child(even) {
    /* 匹配偶数行 */
    background-color: #ddd;
    text-align: center;
    color: white;
}
```
