0

I have the following html

.resources .resource:first-child {
  border-top: 1px solid #D9B310;
}

.resources .resource {
  border-bottom: 1px solid #D9B310;
  padding: 10px 0;
}
<div class="resources">
  <h2 class="text-center">Ресурси</h1>

    <div class="resource">
      <h4>Минерали <span class="resource-quantity">3700</span></h3>
    </div>

    <div class="resource">
      <h4>Газ <span class="resource-quantity">500</span></h3>
    </div>
</div>

the selector without the first-child works fine. But the first-child selector it's not wrking in my case. Can someone tell me why ?

Paolo Forgia
  • 6,572
  • 8
  • 46
  • 58
Angel Miladinov
  • 1,596
  • 4
  • 20
  • 43

3 Answers3

3

Because that the .resource element that you want to stylize is the second child of it's parent, the first child is the h1 tag (careful, your heading tags were not properly closed).

You may be mistaken :first-child with :first-of-type.

  • :first-child only selects the .resource elements that are the first child within their parent container.

  • :first-of-type selects the .resource elements that are the first element matching the given selector (.resource) within their parent container, but not necessarily on the first-child position.

You can either use :nth-child(2) or :first-of-type, as in your case the element is the second child.

.resources .resource:nth-child(2){
  border-top: 1px solid #D9B310;
}

.resources .resource {
  border-bottom: 1px solid #D9B310;
  padding: 10px 0;
}
<div class="resources">
  <h1 class="text-center">Ресурси</h1>

    <div class="resource">
      <h3>Минерали <span class="resource-quantity">3700</span></h3>
    </div>

    <div class="resource">
      <h3>Газ <span class="resource-quantity">500</span></h3>
    </div>
</div>
XCS
  • 27,244
  • 26
  • 101
  • 151
1

Use :first-of-type because it's second child of it's parent.

.resources .resource:first-of-type {
  border-top: 1px solid #D9B310;
}

.resources .resource {
  border-bottom: 1px solid #D9B310;
  padding: 10px 0;
}
<div class="resources">
  <h2 class="text-center">Ресурси</h2>

    <div class="resource">
      <h4>Минерали <span class="resource-quantity">3700</span></h4>
    </div>

    <div class="resource">
      <h4>Газ <span class="resource-quantity">500</span></h4>
    </div>
</div>
Abhishek Pandey
  • 13,302
  • 8
  • 38
  • 68
0

.resources .resource:first-of-type {
  border-top: 1px solid #D9B310;
}

.resources .resource {
  border-bottom: 1px solid #D9B310;
  padding: 10px 0;
}
<div class="resources">
  <h2 class="text-center">Ресурси</h2>

    <div class="resource">
      <h4>Минерали <span class="resource-quantity">3700</span></h4>
    </div>

    <div class="resource">
      <h4>Газ <span class="resource-quantity">500</span></h4>
    </div>
</div>
RïshïKêsh Kümar
  • 4,734
  • 1
  • 24
  • 36