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.