CSS偽類 - :nth-of-type()



CSS :nth-of-type() 偽類根據元素在其同類型兄弟元素(標籤名)中的位置來匹配元素。

語法

:nth-of-type( | even | odd) {
   /* ... */
}

可能的值

  • odd − 此值表示從末尾開始計數的系列中所有奇數編號(例如,1,3,5…等)的兄弟元素。

  • even − 此值表示從末尾開始計數的系列中所有偶數編號(例如,2,4,6…等)的兄弟元素。

  • 函式表示法 (<an+b>) − 此值表示從其父容器末尾開始計數的系列中每an+b個子元素,其中a是正整數,n是從0開始的計數器變數。b是另一個正整數。

CSS :nth-of-type() 示例

以下是如何使用:nth-of-type()選擇器來設定第二個span元素樣式的示例:

<html>
<head>
<style>
   span:nth-of-type(2) {
      background-color: pink;
      color: blue;
   }
</style>
</head>
<body>
   <p>This is a <b>p</b> tag. </p>
   <span>This is first <b>span</b> tag.</span>
   <p>This is a <b>p</b> tag. </p>
   <span>This is second <b>span</b> tag</span>
   <p>This is a <b>p</b> tag. </p>
</body>
</html>

以下是如何設定奇數段落樣式的示例:

<html>
<head>
<style>
   p:nth-of-type(2n+1) {
      background-color: pink;
      color: blue;
   }
</style>
</head>
<body>
   <p>This is first <b>p</b> tag. </p>
   <div>This is first <b>div</b> tag.</div>
   <p>This is second <b>p</b> tag.</p>
   <p>This is third <b>p</b> tag.</p>
   <p>This is fourth <b>p</b> tag.</p>
   <div>This is second <b>div</b> tag..</div>
</body>
</html>
廣告
© . All rights reserved.