Sometimes when we create our CSS, we want to target a certain element. Let’s say if we had an HTML document full of <div>
tags and <span>
tags, but only wanted to target the first of each type to style it some way. We can do that with what’s called the :first-of-type pseudo-class.
A pseudo-class is a way for a CSS selector to have specific styles different from the original styles given. This is dependent on what state the element is in. In this instance, we want to select the first <div>
and the first <span>
so we can style it – no other spans or divs will be selected.
Here is an example to get you started:
<html> <head> <style> body { display: flex; flex-flow: row wrap; } div { height: 100px; width: 200px; border: 1px solid black; margin: 20px; padding: 20px; } /* First of type */ div:first-of-type { background: purple; color: white; } div span:first-of-type { color: red; text-decoration: underline; background: lightblue; } </style> </head> <body> <div>I am the first div<span> I am inside the div and the first span</span><span> I am the second span</span></div> <div>I am the second the div<span> I am inside the div</span><span> I am the second span</span></div> <div>I am the third div<span> I am inside the div</span><span> I am the second span</span></div> <div>I am the fourth div<span> I am inside the div</span><span> I am the second span</span></div> <div>I am the fifth div<span> I am inside the div</span><span> I am the second span</span></div> <div>I am the sixth div<span> I am inside the div</span><span> I am the second span</span></div> <div>I am the seventh div<span> I am inside the div</span><span> I am the second span</span></div> </body> </html>
Here we have a set of divs and spans inside those divs. The CSS selector div:first-of-type
only selects the very first element of its type and styles it. The div span:first-of-type
selects the first span in each div since the div is the parent element.
div:first-of-type
would be the same as saying div:nth-child(1)
Conclusion
In this article we took a look at the :first-of-type pseudo-class. We saw that a pseudo-class is basically just something that describes the state we want the CSS selector to be in when we style it. We also took a look at the general syntax. I would suggest taking a look at other pseudo-selectors and get a feel for them as well!
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.