CSS - choose your first child with a class

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

/*** 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;
}
+4
source share
4 answers

This is probably a bit, but you can use the :notuniversal selector *as follows:

*:not(.child) + .child {
  color: red;
}
<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>
Run codeHide result

Note: . However, any gap in the sequence (another non-child classified div followed by another child class) will repeat the selector.

JSfiddle Demo

+4
source

Maybe something like this:

.parent .child:nth-last-child(4) {
    background-color: #f00;
}

Demo

0

HTML, :

<div class="parent">
  <p>Paragraph</p>
  <div>Broken</div>
  <div class="children">
    <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>

.child:first-child{
    background-color:#f00;
}

fiddle.

0

I find ' : first-of-type ' works well for this kind of thing:

#parent .child:first-of-type {
  background: red;
}

You can also use the same for the latter, if necessary:

#parent .child:last-of-type {
  background: red;
}
-1
source

All Articles