What sets apart :first-child from :first-of-type?

I need help understanding the distinction between element:first-child and element:first-of-type

Let's consider a scenario where you have a div element

div:first-child
→ Refers to all <div> elements that are the first child of their parent.

div:first-of-type
→ Refers to all <div> elements that are the first occurrence of a <div> element within their parent.

Although they might seem similar, they actually function differently.

Can someone please provide clarification on this topic?

Answer №1

A main container can contain multiple smaller containers:

<div class="main">
  <div>Child</div>
  <div>Child</div>
  <div>Child</div>
  <div>Child</div>
</div>

Out of these children, only one can be considered the first. This is identified by :first-child:

<div class="main">
  <div>Child</div> <!-- :first-child -->
  <div>Child</div>
  <div>Child</div>
  <div>Child</div>
</div>

The distinction between :first-child and :first-of-type lies in the fact that :first-of-type matches the first element of its type within the parent, even if it's not the initial child of the container. At this moment, all child elements examined are div, but we'll explore other types shortly.

Conversely, any element marked as :first-child is also inherently

:first-of-type</code. Because the first child here is a <code>div
, it will match both pseudo-classes as well as the tag selector div:

<div class="main">
  <div>Child</div> <!-- div:first-child, div:first-of-type -->
  <div>Child</div>
  <div>Child</div>
  <div>Child</div>
</div>

If you change the type of the first child from div to another like h1, it remains the primary child but no longer the first div. Instead, it now becomes the sole h1. Following this scenario, if there are more div elements after the first child, the next div would then meet the criteria for div:first-of-type. In the provided example, the second child becomes the initial div following the conversion of the first child to an h1:

<div class="main">
  <h1>Child</h1>   <!-- h1:first-child, h1:first-of-type -->
  <div>Child</div> <!-- div:nth-child(2), div:first-of-type -->
  <div>Child</div>
  <div>Child</div>
</div>

It should be noted that :first-child is identical to :nth-child(1).

This indicates that though an element may have just one child matching :first-child at a time, it can possess several children meeting the :first-of-type criteria based on their types. In our instance, the selection .main > :first-of-type (implicitly qualifying :first-of-type) will find two elements rather than one:

<div class="main">
  <h1>Child</h1>   <!-- .main > :first-of-type -->
  <div>Child</div> <!-- .main > :first-of-type -->
  <div>Child</div>
  <div>Child</div>
</div>

The same concept applies to :last-child and :last-of-type: any :last-child is essentially :last-of-type because there are no additional elements following it in the parent. However, since the final div is also the last child, the h1 cannot hold that position despite being the ultimate element of its kind.

:nth-child() and :nth-of-type() behave similarly when using an integer argument (like :nth-child(1) mentioned earlier) with their disparity lying in the number of matches found by :nth-of-type(). This topic is explored further in What is the difference between p:nth-child(2) and p:nth-of-type(2)?

Answer №2

To illustrate the distinction between first-child and first-of-type, I have provided an example below.

    .parent :first-child {
      color: red;
    }

    .parent :first-of-type {
      background: yellow;
    }

    .parent p:first-child {
      text-decoration: line-through;
    }

    /* Does not work */
    .parent div:first-child {
      font-size: 20px;
    }
    /* Use this instead */
    .parent div:first-of-type {
      text-decoration: underline;
    }
    /* This is second child regardless of its type */
    .parent div:nth-child(2) {
      border: 1px black solid;
    }
<div class="parent">
      <p>Child</p>
      <div>Child</div>
      <div>Child</div>
      <div>Child</div>
    </div> 

Answer №3

Understanding the distinction between first-child-type and first-child is crucial, and can be best illustrated with an example. Below is a sample code that demonstrates the difference:

Code #1 for first-of-type:

<!DOCTYPE html>
<html>
<head>
<title>clear everything</title>
<style>
p:first-of-type{
color:red;
}
</style>
<head>
<body>
<p class="p1">some text</p>
<div>
<p class="p2">some text</p>
<div>
<p class="p3">some text</p>
</div>
<p class="p4">some text</p>
</div>
<p class="p5">some text</p>
</body>
</html>

result:

.p1,.p2,.p3 will be styled in red. Even if we move .p1 after the second div, it will still appear red.

Code #2 for first-child:

<!DOCTYPE html>
<html>
<head>
<title>clear everything</title>
<style>
p:first-child{
color:red;
}
</style>
<head>
<body>
<p class="p1">some text</p>
<div>
<p class="p2">some text</p>
<div>
<p class="p3">some text</p>
</div>
<p class="p4">some text</p>
</div>
<p class="p5">>some text</p></body>
</html>

result:

If we move .p2 after the second div, it will not be styled in red as it was in the previous case.

Answer №4

The :first-child pseudo-class specifically targets the initial element within a set of sibling elements only if it holds the position of first child in its parent container. In contrast, :first-of-type focuses on selecting the primary element of a specified type among a series of sibling elements irrespective of its position as the first child in the parent container.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Showing XML content with JavaScript

Trying to parse a simple XML list using JavaScript, but having trouble formatting it the way I need. <TOURS> <MONTH> <TOUR> <NUMBER>1</NUMBER> <VENUE>City Name - Venue Name</VENUE> < ...

Setting text alignment in Bootstrap based on breakpoints

Imagine this code: import React from 'react' import DarkPattern from '../Assets/dark-pattern.jpg' const Profile = () => { return ( <div> <section className="bg-dark text-light text-center " ...

What measures can be taken to stop links from disrupting the style of a Polymer site?

In Polymer, it seems that many styles are inherited from the surrounding document. For example, the code snippet below will display the icon and button with a white foreground color and adjust spacing: <paper-toolbar> <paper-icon-button icon=" ...

Why are my styles not working when referenced from the .module.scss file?

Here is the code snippet from my Sublayout.module.scss file: .pl-6 { padding-left: 6rem !important; } .pr-6 { padding-right: 6rem !important; } .pl-12 { padding-left: 12rem !important; } .pr-12 { padding-right: 12rem !important; } After im ...

Could someone provide a detailed explanation on the functionality of multiple inline nth-child() in CSS?

In this scenario, there is an example provided: html>body>#wrapper>div>div>div:nth-child(1)>div:nth-child(1)>nav { I am curious about the functionality of this code. Could someone dissect each div, ">", and nth-child()? Your ins ...

Iphone not picking up media queries, while browser resize is working perfectly

Hey there, I'm currently using a theme called Bones on my WordPress site, but I'm encountering some difficulties with the responsive menu on my iPhone. Oddly enough, when I manually resize the window, the menu seems to work just fine. Here' ...

Spree Deluxe - Customizing color scheme variables

We're struggling to modify the color variables in Spree Fancy. The documentation suggests creating a variables_override.css.scss file. But where exactly should this file be placed? We've tried adding it under the stylesheets folder in assets and ...

Position the div to float on the right side and then have it drop below on smaller screens

I'm currently working on implementing a design effect similar to the one shown below: on my website (), but I'm struggling with getting the HTML and CSS just right. When I move the map to float up on the right side, it doesn't drop below th ...

There appears to be an issue with the onmousemove function

I am currently troubleshooting an issue with a script that I wrote for my button. Interestingly, the code works flawlessly when I test it on CodePen, but I encountered an error when I attempted to run it in VSCode. Even after trying to recreate the script ...

Apply a watermark specifically to fancybox for images in galleries, excluding non-gallery items

I recently encountered an issue with a FancyBox image gallery on my webpage. I wanted to add a watermark to the gallery items, so I followed an example from the FancyBox page at http://jsfiddle.net/w5gQS/. beforeShow: function () { $('<div class=" ...

only a single backdrop filter can be in use at any given moment

Experimenting with backdrop-filter in Chrome 76. I'm working on a menu with 2 divs, each with a backdrop-filter applied. The first div is displaying the filter effect perfectly, but the second one isn't. Interestingly, when I remove the filter fr ...

Can CSS be used to create an animation effect with just this image?

Is it possible to incorporate a running image of "Pikachu" using CSS instead of creating a heavier GIF format? I have the image link and code below, but need assistance on how to implement it. Can you provide guidance? image: .pikaqiu_run { width: ...

What is the reason for index.html requesting the css or js modules as if they were directories when loading?

I am currently developing a server using expressjs: 'use strict'; var express = require('express'); var logger = require('morgan'); var path = require('path'); var bodyParser = require('body-parser'); va ...

Tips for creating a gap between the <label> element and a form field

I have read through the answers provided, but nothing seems to work for me. My goal is to place a label and 2 small form fields on the same line, with about 90px of space between the label and the fields. I am aiming for a layout similar to the image shown ...

Display a division in C# MVC 4 when a boolean value is true by using @Html.DropDownList

I have multiple divs stacked on top of each other, and I want another div to appear when a certain value is selected. I'm familiar with using JavaScript for this task, but how can I achieve it using Razor? Below is a snippet of my code: <div id=" ...

What is the best way to adjust the size of a Div slideshow using

I need help with creating a slideshow that covers my webpage width 100% and height 500px. The image resolution is 1200*575. Can someone assist me with this? CSS #slide{ width : 100%; height: 500px; } HTML <!DOCTYPE html> <html> ...

What causes the issue when attempting to import multiple CSS files in a Vue.js project using @import more than once?

Currently, I am working on a project that involves one main component and several child components. These components require custom CSS files as well as additional vendor CSS files. A challenge I encountered is that I cannot use the @import "path/to/css/fi ...

Excessive width of Bootstrap container

Encountering a rather simple issue: the bootstrap container inside my navbar is too wide, causing an unwanted horizontal scrollbar as it expands the body. You can view the problematic page here. The theme used for this site can be found here. What's ...

Do Dreamweaver's design and live view display contrasting elements?

Check out the images below: http://gyazo.com/c3ffe1d0a48b717f695d7cbd860eda50.png (Design view) http://gyazo.com/a1e09aacc855c013d349017d0487402d.png (Live & browser view) In the design view, everything appears as intended and looks great. However, i ...

Having two owl carousels on one page is causing some issues

Struggling to implement two owl carousels on my page. Gif: View Gif Here The first carousel (shown at the top in the gif) is functioning perfectly. However, the second one (beneath the first in the gif) is not behaving as expected. Instead of displaying ...