CSS - :first-of-type 偽類



CSS 偽類選擇器:first-of-type 用於選擇和設定其父容器內其型別第一個元素的樣式。此偽類允許您定位並專門將樣式應用於給定容器內某種元素的第一次出現。

CSS 偽類選擇器:first-child 類似於:first-of-type,但存在差異:它不太具體。:first-child 只匹配父元素的第一個子元素;而:first-of-type 匹配指定元素的子元素,即使它不是第一個。

語法

:first-of-type {
   /* ... */ 
}

CSS :first-of-type 示例

以下示例演示了:first-of-type 偽類的用法,應用於<p>標籤,在<div>父元素下。

在此示例中,CSS 規則僅適用於在<div>元素內找到的第一個<p>元素,而不會影響同一容器內的其他<p>元素。

<html>
<head>
<style>
   p:first-of-type {
      color: black;
      background: peachpuff;
      font-weight: 600;
      font-size: 1em;
      font-style: italic;
      padding: 5px;
   }
   div {
      border: 2px solid black;
      margin-bottom: 5px;
   }
</style>
</head>
<body>
   <div>Parent element
      <p>first child looks different due to :first-of-type pseudo-class</p>
      <p>second child, so no change</p>
   </div>
   <div>Parent element
      <h3>h3 tag, so no change</h3>
      <p><b>p</b> tag, and first-of-type of paragraph under this parent.</p>
   </div>
</body>
</html>

以下示例演示了:first-of-type 偽類的用法,應用於<li>標籤,在<ul>父元素下。

在此示例中,CSS 規則僅適用於在<ul>元素內找到的第一個<li>元素,而不會影響同一容器內的其他<li>元素。

<html>
<head>
<style>
   ul li:first-of-type {
      color: black;
      background: yellow;
      font-weight: 600;
      font-size: 1em;
      font-style: italic;
      padding: 5px;
   }
   div {
      border: 2px solid black;
      margin-bottom: 5px;
      width: 300px;
   }
</style>
</head>
<body>
   <div>
      <ul>
         <li>One</li>
         <li>Two</li>
         <li>Three
            <ul>
               <li>Three 1</li>
               <li>Three 2</li>
               <li>Three 3</li>
            </ul>
         </li>      
      </ul>
   </div>
</body>
</html>
廣告

© . All rights reserved.