Can't select with nth-child

Hi, I just started a project and I'm having a problem with the following code: HTML
<body>
<section>
<div class="container">
<h3>lorem ipsum sit</h3>
<h1 class="title">Responsive layouts don't have to be a struggle</h1>
<h2 class="title">Quality Designs</h2>
</div>
</section>
</body>
<body>
<section>
<div class="container">
<h3>lorem ipsum sit</h3>
<h1 class="title">Responsive layouts don't have to be a struggle</h1>
<h2 class="title">Quality Designs</h2>
</div>
</section>
</body>
CSS
.title:nth-child(1) {
color: red
}
.title:nth-child(1) {
color: red
}
The problem is that the nth-child pseudoclass does not select neither the h1, nor the h2. This is because (for some reason) h1 has position 2 (i.e. I can select it by typing nth-child(2)) and h2 has position 3 (same thing). It's like there's a ghost element with the class "title" that there's breaking my styles. If someone knows what's going on here plz explain me, I would appreciate it a lot!
2 Replies
DJR
DJR17mo ago
:nth-child works a little differently. It will start counting from the first child element, which in your case is the <h3>. Your <h3> has no .title class, so the style isn't applied.
Jochem
Jochem17mo ago
you're probably looking for :nth-of-type https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-of-type also, just as a pointer, it looks like you're using h-tags as a way to have different sized text. You should only use them when they have semantic meaning, and a level-3 tag doesn't make sense unless you have level 1 and 2 above it
Want results from more Discord servers?
Add your server