-8

Please tell me why first-child does not work. NEW

How can I set styles for the first child element of .all?

Necessarily!!!!

I don't know the exact index of the desired element.

Necessarily!!!!

#one {
  width: 500px;
  height: 250px;
  border: 1px solid;
  font-size: 0px;
}

#one #two {
  width: 100%;
  height: 50px;
  background: blue;
}

#one .all {
  width: 250px;
  height: 200px;
  background: green;
  display: inline-block;
}

#one .all:first-child(1) {
  background: grey;
}
<div id="one">
  <div id="two"></div>
  <div class="all"></div>
  <div class="all"></div>
</div>
Vector
  • 109
  • 5
  • Maybe [read the docs](https://developer.mozilla.org/en-US/docs/Web/CSS/:first-child) as to how `:first-child` works – j08691 Apr 05 '22 at 20:28
  • 1
    Why doesn’t it work? Because the element is not the first child, and `:first-child()` doesn’t exist; I can only assume you got confused with `:nth-last-child()`. – David Thomas Apr 05 '22 at 20:28

1 Answers1

2

The following syntax is invalid.

#one .all:first-child(1) {}

You might be looking for :nth-child() and got confused as :first-child doesn't take any parameters or arguments.

To solve your problem, you might need to use :nth-of-type() and need to give the index as 2 because this is the second element matching this type:

#one {
  width: 500px;
  height: 250px;
  border: 1px solid;
  font-size: 0px;
}

#one #two {
  width: 100%;
  height: 50px;
  background: blue;
}

#one .all {
  width: 250px;
  height: 200px;
  background: green;
  display: inline-block;
}

#one .all:nth-of-type(2) {
  background: grey;
}
<div id="one">
  <div id="two"></div>
  <div class="all"></div>
  <div class="all"></div>
</div>

Preview

preview

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
  • 1
    `:nth-of-type` is meant to be used with an element, not a class. There's no `:nth-of-class` though, so `#one :nth-of-type(2)` and `#one div:nth-of-type(2)` would work – j08691 Apr 05 '22 at 20:32
  • I don't know the index because there could be a large number of other elements before the desired element. – Vector Apr 05 '22 at 20:33
  • @Vector Lemme think of alternate solution. But there's only JavaScript / jQuery solution possible. – Praveen Kumar Purushothaman Apr 05 '22 at 21:06