I have recently been trying to get my head around why this is not working. Ive started pulling my hair out trying to find a nice solution to a simple problem but every way that I can find to do this just seems messy. Basically what I would like to do is apply some styling to the first child with a specific class within a parent, in my example I am trying to apply a background color of red to the first instance of .class within each .parent. You can see my attempts in the fiddle here.
Here is the final code that I created that is working. The problem is that this seems very messy and I really dont like the fact that I have to set all of the .child classes to red then set all but the first back to white. There must be a cleaner/better way to do this?
HTML
<div class="parent">
<p>Paragraph</p>
<div class="child">Child 1</div>
<div class="child">Child 2</div>
<div class="child">Child 3</div>
<div class="child">Child 4</div>
</div>
<div class="parent">
<p>Paragraph</p>
<div>Broken</div>
<div class="child">Child 1</div>
<div class="child">Child 2</div>
<div class="child">Child 3</div>
<div class="child">Child 4</div>
</div>
CSS
/*** Does Not Work ***/
.child:first-child{
background-color:#f00;
}
/*** Does Not Work ***/
.child:nth-of-type(1){
background-color:#f00;
}
/*** Works But Is Messy! ***/
.child{
background-color:#f00;
}
.child ~ .child{
background-color:#fff;
}