stackoverflow_user
stackoverflow_user

Reputation: 289

How to select first label within div using css?

Hi i want to select first label element within div with classname form_fields.

Below is the code,

 <form>
     <div className="form_fields">
         <span>first span</span>
         <div>first div</div>
         <label>
             <span>Name</span>
         </label>
         <label>Description</label>
     </div></form>

What i have tried?

.fields label:first-child {
    margin: 20px;
}

But this doesnt apply to the first label inside div of class form_fields. How can i do it? thanks.

Upvotes: 3

Views: 3394

Answers (5)

Mr Coder
Mr Coder

Reputation: 66

.form_fields label:nth-of-type(1) {
     color: blue;
 }

Upvotes: 0

user2226755
user2226755

Reputation: 13167

You can choose between 2 pseudo-class :

  • The :first-of-type CSS pseudo-class represents the first element of its type among a group of sibling elements. See doc
  • The :nth-of-type(1) CSS pseudo-class matches elements of a given type, based on their position among a group of siblings. See doc

Solution with :first-of-type :

enter image description here

.form_fields label:first-of-type {
  background:red;
}
<form>
  <div class="form_fields">
    <span>first span</span>
    <div>first div</div>
    <label>
      <span>Name</span>
    </label>
    <label>Description</label>
  </div>
</form>

Upvotes: 1

aarcoraci
aarcoraci

Reputation: 231

I can imagine you are looking to do more than just that but its a great start to ask around here. In HTML and CSS you will find there are several ways to achieve the same results and the path you choose will often be based on personal preferences. In this specific case you have just concept mistakes but you are definitively on the right track.

  1. in your tag, you should change className o just "class".
  2. in your style, change :first-child to :first-of-type
<form>
  <div class="form_fields">
    <span>first span</span>
    <div>first div</div>
    <label>
      <span>Name</span>
    </label>
    <label>Description</label>
  </div>
</form>

<style>
  .form_fields label:first-of-type {
    margin: 20px;
  }
</style>

Upvotes: 1

Brad
Brad

Reputation: 479

.form_fields label:nth-of-type(1) {
    margin: 20px;
}

Upvotes: 1

Mario Cianciolo
Mario Cianciolo

Reputation: 1261

Try with first-of-type pseudo-selector:

.form_fields label:first-of-type {
    margin: 20px;
}

Upvotes: 4

Related Questions