first-of-type
Catch the first element type that's a child of a parent element
Let's say we wanted to target DOM Elements of a particular type inside a parent DOM container say a section
.
<section class="plan">
<div>
Inner Content not in an inner enclosed DIV or DOM Element.
<div>Inner Content 1 in 1st plan DIV</div>
<div>Inner Content 2 in 1st plan DIV</div>
</div>
<div>Content 2 in Red</div>
<div>Content 3 in Red</div>
<div>Content 4 in Red</div>
<div>Content 5 in Red</div>
</section>
<div>Content 1 in Green</div>
<div>Content 2 in Green</div>
If we do section.plan div
it'll target all DIVs inside section.plan
. So a section.plan div { color: blue; }
will make text content in all DIVs in color blue.
But if we do section.plan > div
it'll target all only DIVs that are direct decendants of section.plan
- all first level DIVs under section.plan
. So section.plan > div { border: 1px solid red; }
will not have red borders for the DIVs with Inner Content 1/2 in 1st plan DIV.
But what about section.plan > div:first-child
? This would select the DIV that's the first child of the parent section.plan
. Here's the catch - if the first child of section.plan
is a P like <p>First child is not a DIV</p>
then section.plan > div:first-child
will fail to do anything - since the first child of section.plan
is not a DIV but a P tag. section.plan > div:first-child
does not mean select the first DIV that's the child of section.plan
- it means that if the first child is a DIV then apply the CSS. To catch the first DIV that's a child of section.plan
we use section.plan > div:first-of-type
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<title>fist-of-type</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" />
<style type="text/css">
section.plan div
{
color: blue;
}
section.plan > div
{
border: 1px solid red;
margin: 10px 0;
}
/* Not used any where since first child of section class="plan" isn't a DIV but a P */
section.plan > div:first-child
{
background-color: yellow;
}
section.plan > div:last-child
{
background-color: lightcyan;
}
section.plan > div:first-of-type
{
border:1px dashed black;
}
section.plan ~ div
{
border: 1px solid green;
margin: 10px 0;
}
</style>
</head>
<body>
<div class="container">
<section class="plan">
<p>First child is not a DIV</p>
<div>
Inner Content not in an inner enclosed DIV or DOM Element.
<div>Inner Content 1 in 1st plan DIV</div>
<div>Inner Content 2 in 1st plan DIV</div>
</div>
<div>Content 2 in Red</div>
<div>Content 3 in Red</div>
<div>Content 4 in Red</div>
<div>Content 5 in Red</div>
</section>
<div>Content 1 in Green</div>
<div>Content 2 in Green</div>
</div>
</body>
</html>
first-of-type is supported on all recent browsers, old and new ones.