HTML如何设置偶数和奇数列表项的样式

CSS :nth-child 伪类的解决方案

我们可以分别使用 :nth-child 伪类和 even 和奇数关键字轻松地设置列表的偶数和奇数项的样式。

样式偶数列表项的示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      li:nth-child(even) {
        background: #74d686;
        font-size: 20px;
        color: #ffffff;
      }
    </style>
  </head>
  <body>
    <ul>
      <li>Hello World</li>
      <li>生活终归还得继续。</li>
      <li>Hello World</li>
    </ul>
  </body>
</html>

样式奇数列表项的示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      li:nth-child(odd) {
        background: #74d686;
        font-size: 20px;
        color: #ffffff;
      }
    </style>
  </head>
  <body>
    <ul>
      <li>Hello World</li>
      <li>生活终归还得继续。</li>
      <li>Hello World</li>
    </ul>
  </body>
</html>

在我们的最后一个例子中,看看如何为无序列表的奇数项和偶数项设置样式。

“奇数”和“偶数”列表项的样式示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      li:nth-child(odd) {
        background: #74d686;
        font-size: 24px;
        color: #ffffff;
      }
      li:nth-child(even) {
        background: #d6d6d6;
        font-size: 20px;
        color: #666;
      }
    </style>
  </head>
  <body>
    <ul>
      <li>Hello World</li>
      <li>生活终归还得继续。</li>
      <li>Hello World</li>
      <li>生活终归还得继续。</li>
    </ul>
  </body>
</html>
日期:2020-06-02 22:15:12 来源:oir作者:oir