0

Here is the code:

CSS:

div.colored {
    width: 300px;
    height: 100px;
    margin-bottom: 20px;
    border: 1px solid black;
}
div.colored:first-child {
    background-color: red;
}
div.colored:last-child {
    background-color: blue;
}    
div.nocolor {
    width: 300px;
    height: 100px;
    margin-bottom: 20px;
    border: 1px solid black;
}

HTML:

<p>Test 1:</p>
<div>
<div class="colored"></div>
<div class="colored"></div>
</div>

<p>Test 2:</p>
<div>
<div class="nocolor"></div>
<div class="colored"></div>
<div class="colored"></div>
<div class="nocolor"></div>
</div>

The first test does what I'd expect. The first div.colored is red and the second (last) is blue. In the second test, there are four divs. The first and last div.colored are not colored. Have I coded my css incorrectly?

1 Answers1

2

first-child and last-child refer to the first and last children of the parent div, not the first and last instance of a class. So in the jsfiddle below, .nocolor are the first and last children of div.parent1. If you wrap the middle two .colored in div.parent2, they will become the first and last children of div.parent2 and they will receive the color.

http://jsfiddle.net/cbsteph/dtuhdnbe/

<div class="parent1">
 <div class="nocolor"></div>
    <div class="parent2">
        <div class="colored"></div>
        <div class="colored"></div>
    </div>
 <div class="nocolor"></div>
</div>
Steph
  • 340
  • 5
  • 22