I have the following code:
div:nth-child(1) {
background-color: red;
}
<h1>Boxes</h1>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
I expect the div with the contents 1st to be selected, but that’s not the case. If, however, I remove the h1 element, then it works as expected. Why?
The problem you’re having is the selector itself:
:nth-child(); this finds the element to which it’s attached, thedivwhich is the nth-child of its parent.As you’re selecting:
This won’t match anything; since the
h1element is the first-child/:nth-child(1)of the shared parent.To adapt, you need to use either:
JS Fiddle demo.
Or create a new parent to enclose the
divelements.JS Fiddle demo.
In supporting browsers, you could also use
:nth-of-type(1):JS Fiddle demo.
References:
:nth-of-type().