The amazing CSS selectors family! One of the most helpful tools we can use when styling our website. In today’s post, 😃 we’ll examine the unstoppable battle of nth-child()
VS nth-of-type()
selectors. They both allow you to target HTML elements based on their position within a parent, but they achieve that differently.
The moment to clarify the key difference between them and how to use each effectively to get the styling we want has finally come! 🤓
So, let’s proceed by analyzing and comparing these amazing pseudo-classes! 💻 ✨
Preparing our HTML structure
We begin with an HTML code snippet by creating a <section>
element as the parent, which contains some <p>
and <div>
children.
<section>
<p>I'm the first paragraph</p>
<div>I'm the first div</div>
<p>I'm the second paragraph</p>
<div>I'm the second div</div>
<p>I'm the third paragraph</p>
<div>I'm the third div</div>
</section>
HTMLBelow, we can see what is rendered on the screen for now. Three paragraphs and three div elements. Note that I have kept the default styling: black text on a white background.
The nth-child selector
The :nth-child()
selector targets the HTML element declared inside the parentheses, regardless of its type. In the code snippet below, we pick the second child (which happens to be a div) by placing the number 2 inside the parentheses.
section :nth-child(2) {
color: white;
background-color: magenta;
}
CSSThe image below shows that the second child takes on our attributes.
You may also like 🎬
The nth-of-type selector
The :nth-of-type()
selector targets HTML elements based on their type. In the following code snippet, we pick the second <p>
element by placing the number 2 inside the parentheses ()
and specifying the type p
before the selector.
section p:nth-of-type(2) {
color: white;
background-color: magenta;
}
CSSThe image below shows that the styling is now applied to the second paragraph instead of the second child.
We can also try to do the same with our <div>
elements. Let’s change the type, in front of our selector, from p
to div
. What would happen then?
section div:nth-of-type(2) {
color: white;
background-color: magenta;
}
CSSWe now notice that the styling is removed from the second paragraph and applied to the second div. Cool huh? 😎
By learning correctly when and how to use each selector, we can ensure that our CSS targets exactly the elements we intend and help us achieve more precise and effective styling. Happy coding! 🎉 👩💻
🌼 Hope you found my post interesting and helpful. Thanks for being here! 🌼