I recently tried to understand why this is not working. Ive started to pull my hair, trying to find a good solution to a simple problem, but every way I can find to do this just seems messy. Basically, what I would like to do is apply some style to the first child with a specific class inside the parent, in my example I am trying to apply the background color of red to the first instance of .class in each .parent. You can see my attempts at the violin here .
Here is the last code I created that works. The problem is that it seems very dirty, and I really don't like the fact that I have to set all .child classes to red and then set everything but the first back to white. Should there 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
.child:first-child{
background-color:#f00;
}
.child:nth-of-type(1){
background-color:#f00;
}
.child{
background-color:#f00;
}
.child ~ .child{
background-color:#fff;
}
source
share