MrGood
MrGood

Reputation: 545

Can't use first-of-type selector with child selector

I'm trying to target the first instance of a .row directly in it's .page-container parent. I can't get the :first-of-type selector to properly target the first instance of .row.

.page-container > .row:first-of-type {
  background: blue;
}
<div class="page-container">
  <div class="row">Target This Row</div>
  <div class="row">Don't Target</div>
  <div class="row">Don't Target
    <div class="row">Don't Target</div>
  </div>
</div>

Please help me target only the first instance of .row that is a direct descendant of .page-container.

Upvotes: 1

Views: 48

Answers (3)

zer00ne
zer00ne

Reputation: 43880

I usually ignore class or id all together and focus on the tag names, then if it's too broad, I narrow it down by adding class or id to parent.

div > div:first-of-type {
  background: blue;
}
div.page-container > div:first-of-type {
  border: 3px solid red;
}
p:first-of-type {
  color: blue
}
p:last-of-type {
  color: red;
}
<p>Example #1 in blue background</p>
<p>Example #2 in red border</p>
<div class="page-container">
  <div class="row">Target This Row</div>
  <div class="row">Don't Target</div>
  <div class="row">Don't Target
    <div class="row">Don't Target</div>
  </div>
</div>

Upvotes: 0

Rounin
Rounin

Reputation: 29453

I ran across this issue relatively recently.

The issue is that :first-of-type specifically means first-of-this-type-of-element and it cannot (and does not) apply to classes.

In order to have a selector that applies to classes, we will need either a :first-of-class or a :first-of-query (which can select anything - including classes) - and, so far, neither exist.

Consequently you need something like this:

.page-container div:first-of-type.row

which means:

the first div nested inside .page-container - but only if it also happens to have the class .row.

Upvotes: 3

Justin Smith
Justin Smith

Reputation: 385

I think what you want is

.page-container > .row:first-child {
    background: blue;
}

Upvotes: 0

Related Questions