15
votes

Should this work am I going crazy?

.project.work:first-child:before {
  content: 'Projects';
}
.project.research:first-child:before {
  content: 'Research';
}
<div class="project work">
  <p>abcdef</p>
</div>
<div class="project work">
  <p>abcdef</p>
</div>
<div class="project work">
  <p>abcdef</p>
</div>
<div class="project research">
  <p>abcdef</p>
</div>

projects:first-child works fine, research:first-child doesn't stick. Any ideas?

Demo It doesn't work, but whats the best way to achieve this?

3
:first-child only selects the first child. Nothing else.BoltClock
.project.research:first-child Isn't that the first of its kind though?uriah
It is, but it's not the first child of its parent.BoltClock
So it's looking at the parent not at the child? Should I use Jquery then to select it?uriah
why use first-child? couldn't you just use .project.work p:before and .project.research p:beforeLast Rose Studios

3 Answers

14
votes

:first-child only selects the first child of its parent. Nothing else.

As mentioned in a few of my other answers on the site (1 2 3 4), there is no :first-of-class pseudo-class. If you are looking to apply styles to the first of each class of your div elements, a solution is to apply the styles to all children of that class, and a general sibling selector to undo the styles from subsequent siblings.

Your CSS would then look like this:

.project.work:before {
    content: 'Work';
}

.project.research:before {
    content: 'Research';
}

.project.work ~ .project.work:before, 
.project.research ~ .project.research:before {
    content: none;
}
1
votes

From the specification:

Same as :nth-child(1). The :first-child pseudo-class represents an element that is the first child of some other element.

.project.research is not the first child of its parent.

0
votes

I believe you want this CSS:

.project.work p:first-child:before {content:'Projects';}
.project.research p:first-child:before {content:'Research';}

or

.project.work > p:first-child:before {content:'Projects';}
.project.research > p:first-child:before {content:'Research';}

Updated fiddle

That matches the first child of an element with the classes "project" and "work" (or "project" and "research"). You don't have to use p:first-child if it may not be a p element, you could use *:first-child instead.