uriah
uriah

Reputation: 2583

first-child not working

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?

Upvotes: 15

Views: 36650

Answers (3)

BoltClock
BoltClock

Reputation: 724452

: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;
}

Upvotes: 15

Felix Kling
Felix Kling

Reputation: 817128

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.

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1075597

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.

Upvotes: 0

Related Questions