Hello there! Today, we’ll explore how the CSS nth-of-type()
selector works. This powerful CSS selector allows us to target every nth child HTML element of a specific type within its parent container.
Below, I prepared some examples to analyze this amazing pseudo-class thoroughly.
Basic HTML structure
We begin with the HTML structure. We create an <article>
HTML element. It contains two headings (<h1>
, <h2>
) elements. Also, we include some <p>
and <div>
HTML elements. The example may seem slightly complicated, but it is the right way to understand just how useful 🛠 tool this selector can be. 😃
For now, we’ll maintain the default styling with a white background and black text.
🔖 Please note that this HTML code snippet will be used across all examples.
<article>
<h1>Explore India</h1>
<h2>India's Top Ten Attractions</h2>
<p>Here goes the 1st paragraph about India's attractions</p>
<p>Here goes the 2nd paragraph about India's attractions</p>
<h2>India's Food</h2>
<div>Here goes text about India's cusine</div>
<div>Here goes text about India's cusine</div>
</article>
HTMLBelow, we can see what is rendered on the screen 💻 for now. It’s just a simple article in a newspaper 🗞 or on the internet. At least as articles were once upon a time 😂 just text, no images, and no special styling. Don’t worry; it works well for us!
Targeting a specific HTML element
Now let’s explore how this selector works. We start by using the nth-of-type()
selector, preceded by h2
, and placing the number 1
inside the parentheses ()
. This targets the very first <h2>
element within our <article>
parent.
article h2:nth-of-type(1) {
color: white;
background-color: magenta;
}
CSSIn the following image, we can see the result of the applied nth-of-type
selector.
Targeting all elements of a specific type
We continue and dive a bit deeper! We place h2
before our nth-of-type()
selector, but this time, we add the n
inside the parentheses
()
. By doing so, we target all <h2>
elements within our parent element.
The n
in nth-of-type(n)
enables the selector to match elements at any position among siblings. This means you can apply styles to all matching elements without specifying an exact position, ensuring that every instance is included.. 😎
article h2:nth-of-type(n) {
color: white;
background-color: magenta;
}
CSSIn the image below, we notice the styling applied to all <h2>
HTML elements after using the nth-last-of-type(n)
selector.
You may also like 🎬
Targeting elements of various types
Additionally, we have the option to use the nth-of-type()
selector to target more than one different type of HTML elements. In our case, we set the p:nth-of-type(1)
to target the first <p>
element and also the div:nth-of-type(2)
to target the second <div>
element.
article p:nth-of-type(1),
article div:nth-of-type(2) {
color: white;
background-color: magenta;
}
CSSThis is how it currently looks on the screen 💻. Cool huh? 😃 ✨
🌼 Hope you found my post interesting and helpful. Thanks for being here! 🌼