Gaylord.P
Gaylord.P

Reputation: 1468

CSS and first-child

In CSS, I select "first-child". I want only <div class="b">1</div> on red background. I don't understand

div {
  height: 50px;
  margin-bottom: 10px
}

.a .b:first-child {
  background: red
}
<div class="a">
  <div class="b">1</div>
  <div class="c">
    <div class="b">2</div>
    <div class="b">3</div>
    <div class="b">4</div>
  </div>
</div>

Upvotes: 0

Views: 30

Answers (2)

smilebomb
smilebomb

Reputation: 5483

I think you want your first-child pseudo-class on .a, not .b.

div {
  height: 50px;
  margin-bottom: 10px
}

.a:first-child {
  background: red
}
<div class="a">
  <div class="b">1</div>
  <div class="c">
    <div class="b">2</div>
    <div class="b">3</div>
    <div class="b">4</div>
  </div>
</div>

Upvotes: 0

SLaks
SLaks

Reputation: 887305

.a .b:first-child means any .b:first-child that is a descendant of .a. Space is the descendant combinator; it doesn't link :first-child to .a in any way.

You want a direct child of .a, using the child combinator: .a > .b.

Upvotes: 1

Related Questions