Child element

<div class="recurse">
	<div>
		<img src="" alt="">
	</div>
	<div>
		<h4></h4>
		<p></p>
	</div>
</div>

Now I want to give this div padding: I am using this CSS →

.recurse:nth-child(2) {
    border: 2px solid red;
    padding: 20px;
}

Am I not using the right CSS?

You almost got it right, you’re just missing the reference to the div element. The following works
.recurse div:nth-child(2) {
border: 2px solid red;
padding: 20px;
}

2 Likes

Seems I am sleep deprived. My CSS is at;east of Intemediate level, but got delusioned because of over thinking. I thought:

.recurse div:nth-child(2) =
nth child of the div’s child elements, which would pe p for the 2nd div and first div will not have: nth-child(2)

I think the reason a reference to div is needed because without it the CSS is not specific enough since the recurse class could be applied to more than one element type. By including div you are saying which element type within that class you are tageting which raises the specificity. Also I think that the nth-child selector is always preceded by an element.

1 Like

:nth-child refers to that elements position within its current structure.

The fact you said div:nth-child is immaterial as far as that element’s position calculation is concerned.

All it means is that the css will find the second child no matter what element it is. If the second child is a p tag then your rule fails to be applied because you have added div to the front.

The css will only apply to a second child but only if that second child happens to be a div when using your css The css doesn’t count divs only; it counts all the child elements no matter their variety.

You could say .test:nth-child(2) but that doesn’t mean look for the second of .test. It means look for the 2nd child and if it also happens to have a class of test then apply the css.

4 Likes