nth-child()

CSS :nth-child() Pseudo Class

The :nth-child() pseudo-class selects and adds styles to elements based on their index.

The :nth-child() can be specified by a number, a keyword, or a formula.

Keyword values

Keyword values

odd

Represents those elements whose numeric position is odd (e.g 1, 3, 5, 7 etc.).

even

Represents those elements whose numeric position is even (e.g 2, 4, 6, 8 etc.).

Functional notation

Functional notation

<An+B>

Represents those elements whose numeric position matches the pattern An+B (for every positive integer or zero value of n). The first element’s index is 1, and n in the formula starts from 0. The values A and B must be integers.

Version

Version

Selectors Level 4

Selectors Level 3

Syntax

Syntax

:nth-child() {
  css declarations;
}

Example of the :nth-child selector:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      p:nth-child(3) {
        background: #ccc;
      }
    </style>
  </head>
  <body>
    <h2>:nth-child selector example</h2>
    <div>
      <p>Paragraph 1</p>
      <p>Paragraph 2</p>
      <p>Paragraph 3</p>
      <p>Paragraph 4</p>
    </div>
  </body>
</html>

Example of “odd” and “even” keywords:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      p:nth-child(odd) {
        background: #1c87c9;
        color: #eeeeee;
      }
      p:nth-child(even) {
        background: #666666;
        color: #eeeeee;
      }
    </style>
  </head>
  <body>
    <p>The first paragraph.</p>
    <p>The second paragraph.</p>
    <p>The third paragraph.</p>
  </body>
</html>


请遵守《互联网环境法规》文明发言,欢迎讨论问题
扫码反馈

扫一扫,反馈当前页面

咨询反馈
扫码关注
返回顶部