关键字值

odd

选择具有奇数索引号的元素(例如 1、3、5、7 等)。

even

选择具有偶数索引号的元素(例如 2、4、6、8 等)。

CSS :nth-last-child 伪类

:nth-last-child() 伪类根据元素的索引从最后一个元素开始向上选择元素。

:nth-last-child() 可以由数字、关键字或者公式指定。

功能符号

<An+B>

选择其数字位置与模式 An+B 匹配的元素(对于 n 的每个正整数或者零值)。
第一个元素的索引是1,公式中的n从0开始。
A和B的值必须是整数。

语法

:nth-last-child() {
  css declarations;
}

:nth-last-child() 选择器示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      p:last-child {
        background-color: #1c87c9;
        color: #fff;
      }
    </style>
  </head>
  <body>
    <h2>:nth-last-child selector example</h2>
    <p>生活终归还得继续。...</p>
    <p>生活终归还得继续。...</p>
  </body>
</html>

“奇数”和“偶数”关键字的示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      p:nth-last-child(odd) {
        background: #1c87c9;
        color: #eee;
      }
      p:nth-last-child(even) {
        background: #666;
        color: #eee;
      }
    </style>
  </head>
  <body>
    <h2>:nth-last-child selector example</h2>
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
    <p>Paragraph 3</p>
  </body>
</html>

带有 <table> 标签的 :nth-last-child() 示例:

<!DOCTYPE html>
<html>
  <head>
    <style>
      table {
        border: 1px solid #8EBF41;
        border-spacing: 10px;
        font-family: sans-serif;
      }
      table tr {
        background-color: #cccccc;
      }
      /* Selects the last three elements */
      tr:nth-last-child(-n+3) {
        background-color: #8EBF41;
      }
      table tr td {
        padding: 10px;
      }
      /* Selects every element starting from the second to last item */
      tr:nth-last-child(n+2) {
        color: #ffffff;
      }
      /* Select only the last second element */
      tr:nth-last-child(2) {
        font-weight: 900;
      }
    </style>
  </head>
  <body>
    <h2>:nth-last-child selector example</h2>
    <table>
      <tbody>
        <tr>
          <td>First row</td>
        </tr>
        <tr>
          <td>Second row</td>
        </tr>
        <tr>
          <td>Third row</td>
        </tr>
        <tr>
          <td>Fourth row</td>
        </tr>
        <tr>
          <td>Fifth row</td>
        </tr>
      </tbody>
    </table>
  </body>
</html>

带有 <li> 标签的 :nth-last-child() 示例:

<!DOCTYPE html>
<html>
  <head>
    <style>
      /* If there are at least three list items, style them all */
      li:nth-last-child(n+3),
      li:nth-last-child(n+3) ~ li {
        color: #8EBF41;
      }
    </style>
  </head>
  <body>
    <h2>:nth-last-child selector example</h2>
    <ol>
      <li>List Item One</li>
      <li>List Item Two</li>
    </ol>
    <ol>
      <li>List Item One</li>
      <li>List Item Two</li>
      <li>List Item Three</li>
      <li>List Item Four</li>
      <li>List Item Five</li>
      <li>List Item Six</li>
    </ol>
  </body>
</html>
日期:2020-06-02 22:14:39 来源:oir作者:oir