31
loading...
This website collects cookies to deliver better user experience
first-child
selector is one such selector. Using the first-child
selector, you can target the element which is the first child of its parent element. This means if you want to target the first <li>
of an unordered list or <ul>
you can use the :first-child
selector to target the first “li” element. The code for it would look similar to the following :ul li:first-child{
color:red;
}
<li>
of the <ul>
and change its color to red. This is a really simple and useful property. However, remember that :first-child
would work only when the element you are targeting is the first child of the parent element. This means that if there is any other sibling element before the element you are targeting, then the first-child property would NOT work as expected. Let’s consider the following example :<div>
<h1>Some Heading</h1>
<p>My first paragraph</p>
<p>My second paragraph</p>
</div>
<style>
/* This would NOT work as expected ! */
div p:first-child{
color:red;
}
</style>
<p>
within the <div>
is being targeted. However, this would NOT work because the <p>
is technically NOT the first child of the <div>
. The first child of the <div>
is the <h1>
tag.first-of-type
selector. The first-of-type selector would target the elements which are of a “certain type or tag” and are the first ones of its type within its parent element. To understand this clearly please take a look at the following example :<div>
<h1>Some Heading</h1>
<p>My first paragraph</p>
<p>My second paragraph</p>
</div>
<style>
/* This would work ! */
div p:first-of-type{
color:red;
}
</style>
<div>
would have the text color as red. The key here is to understand that the <p>
or paragraph is NOT technically the first child and that when you want to target the paragraph or <p>
you should target the <p>
which is the first child of its parent <div>
and of the ‘certain’ type or of the ”