With the onset of CSS3 a lot of new selectors were introduced. Many of these new selectors have been of a lot of help to us. The 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;
}
The above code would target the first <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>
In the above example, you can notice that the first <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.
So, how to make the :first-child work in CSS ?
If there are other sibling elements before the “first child element” that you are targeting, you should use the 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>
In the example above, the first paragraph within the <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 ”
type “.
Hope you understood the concept and liked the article. Please like us on Facebook and follow us on Twitter.
The post How to make CSS first-child work first appeared on MoreOnFew.
Top comments (0)