What are the differences between :first-child and :first-of-type in CSS

CSS allows developers to style an element via its pseudo-class which is used to define a special state of an element. The most common cases are visited links and hovering links.

In this article we talk about the misunderstanding of 2 pseudo classes, :first-child and :first-of-type.

Table of Contents

:fist-child

The :first-child pseudo-class matches a specified element that is the first child of its parent. You use it when you want to pick the first li tag within an ul.

In the example below, we try styling the first li tag with li:first-child pseudo. As you see in the image, the first li in 2 lists turn red. Using :first-child returns any first li tag within any ul tag.

<ul class="list">
	<li>Cascading Style Sheets (CSS) is a style sheet language used to describe the look and formatting of HTML pages</li>
	<li>CSS can be applied to individual HTML elements </li>
	<li>CSS styles are usually placed in external files, called "style sheets"</li>
	<li>The browser reads these style sheets and applies them to each element on the page according to instructions from their selectors</li>
	<li>Styles can also be applied using inline code within an HTML document's head section or inside an individual tag like an h1, for example</li>
	<li>A selector is a type of rule that tells the browser which part of the page should have its styling changed by this particular rule</li>
	<li>Selectors are written as a type of markup followed by curly brackets {} containing one or more space-separated values, with each value representing one target element(s) for that rule</li>
</ul>
<ul>
	<li>Why you should learn CSS</li>
	<li>You can also use "classes" which allow you to apply one set of styles to multiple elements on the page </li>
</ul>

<style type="text/css">
	li:first-child{
		color: red;
	}
</style>

:first-of-type

The :first-of-type selects the first element of the selectors. You use it when you want to pick the first element among a list like div.wrapper.

<div>What is a CSS Pseudo-selector?</div>
<p>Examples of CSS Pseudo-selectors</p>
<p>How to use pseudo selectors in your code</p>
<span>Why are they used?</span>
<p>When should you not use them?</p>
<span>Where can I find more information on this subject? </span>

<style type="text/css">
	p:first-of-type{
		color: blue;
	}
	span:first-of-type{
		color: orange;
	}
</style>

Leave a Comment

Your email address will not be published. Required fields are marked *


Scroll to Top

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close