Reputation: 289
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
Reputation: 13167
You can choose between 2 pseudo-class :
:first-of-type
CSS pseudo-class represents the first element of its type among a group of sibling elements. See doc:nth-of-type(1)
CSS pseudo-class matches elements of a given type, based on their position among a group of siblings. See doc:first-of-type
:.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
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.
<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
Reputation: 1261
Try with first-of-type
pseudo-selector:
.form_fields label:first-of-type {
margin: 20px;
}
Upvotes: 4