Jesse Elser
Jesse Elser

Reputation: 976

Using Nth-Child With Span Elements - All Span Elements Are Odd For Some Reason

I'm trying to use the nth-child pseudo selector to target even an odd spans in a containing div. My HTML markup looks like this.

<div class="load-data">
<span>Company: Heavy Haul LLC.</span><br> 
<span>Name: John Smith</span><br> 
<span>Phone: (123)-456-7890</span><br> 
<span>Position: Chase</span><br> 
<span>From: Knoxville, TN</span><br> 
<span>To: Nashville, TN</span><br> 
<span>Date: 03/02/2016</span><br> 
<span>Rate: $250 Day Rate</span><br> 
</div>

And my CSS looks like this:

.load-data {
 border: 1px solid #454545;
 background-color: #121212;
 display: inline-block;
 margin: 5px 10px;
 text-align: left;
}
.load-data > span {
 padding: 5px;
 display: inline-block;
}
.load-data span:nth-child(even) {
 color: #ff6400;
}
.load-data span:nth-child(odd) {
 color: #ff9900;
}

But for some reason every span element has the color of ff9900. Why would they all be odd numbers?

For debugging I did try using nth-child(5) just to see what happens and the third line was selected for some reason instead of the fifth one.

I'm not understanding why this is happening.

Upvotes: 1

Views: 247

Answers (1)

zer00ne
zer00ne

Reputation: 43880

Choices

  1. Use nth-of-type instead, It's counting <br> as a child.

  2. Use nth-child and div instead of span and get rid of the <br>.

If you simply remove the <br> and use nth-child you'll get a mess since <span> are inline, see second example.

At that point you either change the<span> by assigning this to your CSS:

span { display: block; }

Or change <span> into <div>

Snippet

.load-data span:nth-of-type(even) { background: blue; }
.load-data span:nth-of-type(odd) { background: red; }
.x span:nth-child(even) { background: blue; }
.x span:nth-child(odd) { background: red; }
<div class="load-data">
<span>Company: Heavy Haul LLC.</span><br> 
<span>Name: John Smith</span><br> 
<span>Phone: (123)-456-7890</span><br> 
<span>Position: Chase</span><br> 
<span>From: Knoxville, TN</span><br> 
<span>To: Nashville, TN</span><br> 
<span>Date: 03/02/2016</span><br> 
<span>Rate: $250 Day Rate</span><br> 
</div>
<br><br>
<div class="x">
<span>Company: Heavy Haul LLC.</span>
<span>Name: John Smith</span>
<span>Phone: (123)-456-7890</span>
<span>Position: Chase</span>
<span>From: Knoxville, TN</span> 
<span>To: Nashville, TN</span> 
<span>Date: 03/02/2016</span>
<span>Rate: $250 Day Rate</span> 
</div>

Upvotes: 2

Related Questions