Angel Miladinov
Angel Miladinov

Reputation: 1655

css first child not wokring

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 ?

Upvotes: 0

Views: 67

Answers (3)

XCS
XCS

Reputation: 28147

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>

Upvotes: 3

.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>

Upvotes: 0

Abhishek Pandey
Abhishek Pandey

Reputation: 13558

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>

Upvotes: 1

Related Questions