Home >Web Front-end >CSS Tutorial >:first-child vs. :first-of-type: When Should I Use Each CSS Pseudo-class?

:first-child vs. :first-of-type: When Should I Use Each CSS Pseudo-class?

Barbara Streisand
Barbara StreisandOriginal
2024-12-09 04:06:18867browse

:first-child vs. :first-of-type: When Should I Use Each CSS Pseudo-class?

Element Selection with :first-child vs. :first-of-type

In CSS, the pseudo-classes :first-child and :first-of-type both select elements based on their position within their parent element. However, they differ in how they define "first."

Element:first-child

:first-child selects the first child element of its specified parent, regardless of its element type. In the example provided:

div:first-child

This selector would match all

elements that are the first child of their parent element. If the parent element contains any other element types, they will not be selected.

Element:first-of-type

:first-of-type selects the first instance of a specific element type within its parent. It will match the first

element, even if it is not the first child overall. For example:

div:first-of-type

In the provided HTML:

<div class="parent">
  <div>Child</div>
  <h1>

:first-of-type would select the

with the class "parent" as its first instance of a
element, while the

with the id "first" would be the first instance of an

element.

Key Differences

  • Element Hierarchy: :first-child matches based on child order, while :first-of-type matches based on element type and position within that type.
  • Number of Matches: :first-child can only match one element per parent, while :first-of-type can match multiple elements of the same type.
  • Specificity: :first-of-type generally has higher specificity than :first-child, meaning it will take precedence in CSS rules.

Example Usage

Use :first-child to select:

  • The first list item in an unordered list: ul li:first-child
  • The title of the first blog post in a list: article .blog-post:first-child h2

Use :first-of-type to select:

  • The first heading (

    ,

    , etc.) in a document: body :first-of-type

  • The first button in a form: form button:first-of-type

The above is the detailed content of :first-child vs. :first-of-type: When Should I Use Each CSS Pseudo-class?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn