The top answer will only work under very strict circumstances and a limited HTML structure. It will lead to issues when you are trying to select elements by a CSS class or other trait. Let me explain, in the following code:
<div class="divWrapper">
<div>1</div>
<div>2</div>
<div>3</div>
<br>
<div>4</div>
<div>5</div>
<div>6</div>
<br>
<div>7</div>
<div>8</div>
<div>9</div>
</div>
Let's say we want to give the 7th div within .divWrapper
a light blue background, if you thought this would work, you are wrong:
.divWrapper > div:nth-child(7) {
background: lightblue;
}
This happens because even though we selected children that are divs, :nth-child()
actually counts not only divs, but all HTML elements within that scope as valid children, therefore the code above paints the 6th div instead of the 7th, because it considered the <br>
tag in-between as a valid child. This can make things very confusing and break the intended design of your website if you were to add new HTML elements.
This is why I recommend using :nth-of-type()
instead, if you are trying to target a CSS class or other attributes, just like with :eq()
in jQuery.
This does the job:
.divWrapper > div:nth-of-type(7) {
background: lightblue;
}
You can see this example in this codepen: https://codepen.io/techbawz/pen/ZEYpBPe or you can run the code directly on this answer.
Hope this helps.
.divWrapper {
width:100%;
text-align: center;
}
.divWrapper > div {
color: white;
width: 50px;
height: 20px;
background: black;
display: inline-block;
margin: .5em;
}
/* We paint the first div within divWrapper green. Works fine! So far... */
.divWrapper > div:nth-child(1) {
background: green;
}
/* We try to paint the 7th div red. It doesn't work, because our selector is not only considering all divs that are childs of divWrapper, but also the <br> tags that are HTML tags which are children of divWrapper */
.divWrapper > div:nth-child(7) {
background: red;
}
/* using nth-of-type, our selector DOES paint the 7th div */
.divWrapper > div:nth-of-type(7) {
background: lightblue;
}
<div class="divWrapper">
<div>1</div>
<div>2</div>
<div>3</div>
<br>
<div>4</div>
<div>5</div>
<div>6</div>
<br>
<div>7</div>
<div>8</div>
<div>9</div>
</div>