Skip to content

表格斑马纹

选择器nth-child

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

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

用法

css
selector:nth-child (number){
    /* 样式 */
}
selector:nth-child (number){
    /* 样式 */
}
  • odd:奇数
  • even:偶数

W3School介绍:

示例

图片

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>
 <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;
}
#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;
}

更新于: