生命之风的低语
Whispers in the Wind of Life.

CSS伪类选择器控制单数和双数子节点的不同样式

秀秀 发布于 2024-6-6 16:40    50 次阅读

在 CSS 中,可以使用 :nth-child 伪类选择器来控制单数和双数子节点的不同样式。以下是一些示例,说明如何使用这些选择器来为奇数和偶数子节点应用不同的样式。

基本示例

假设有以下 HTML 结构:

<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
  <li>Item 5</li>
</ul>

我们希望为奇数项和偶数项应用不同的样式,可以这样做:

/* 选择所有奇数子节点 */
ul li:nth-child(odd) {
  background-color: lightblue;
}

/* 选择所有偶数子节点 */
ul li:nth-child(even) {
  background-color: lightgreen;
}

上述 CSS 代码将第一个、第三个和第五个 <li> 元素的背景色设置为 lightblue,而第二个和第四个 <li> 元素的背景色设置为 lightgreen

更复杂的示例

假设我们有更复杂的 HTML 结构,例如一个表格,我们希望对表格行应用不同的样式:

<table>
  <tr>
    <td>Row 1, Cell 1</td>
    <td>Row 1, Cell 2</td>
  </tr>
  <tr>
    <td>Row 2, Cell 1</td>
    <td>Row 2, Cell 2</td>
  </tr>
  <tr>
    <td>Row 3, Cell 1</td>
    <td>Row 3, Cell 2</td>
  </tr>
  <tr>
    <td>Row 4, Cell 1</td>
    <td>Row 4, Cell 2</td>
  </tr>
</table>

我们可以这样应用不同的样式:

/* 选择所有奇数行 */
table tr:nth-child(odd) {
  background-color: #f2f2f2;
}

/* 选择所有偶数行 */
table tr:nth-child(even) {
  background-color: #ffffff;
}

上述代码将奇数行的背景色设置为浅灰色,而偶数行的背景色设置为白色。

使用其他的伪类选择器

除了 :nth-child 之外,还有一些其他的伪类选择器可以帮助选择特定的子节点。例如,:first-child:last-child 选择器可以选择第一个和最后一个子节点:

/* 选择第一个子节点 */
ul li:first-child {
  font-weight: bold;
}

/* 选择最后一个子节点 */
ul li:last-child {
  font-style: italic;
}

通过组合这些选择器,您可以实现更复杂和精细的样式控制。