Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I select the first or the last child with CSS correct?

I want to select the first and the last child with CSS but it does not work. Please take a look at my Fiddle and help me:

.area {
  height: 100px;
  width: 100px;
}

.area:first-child {
  background-color: red;
}

.area:last-child {
  background-color: green;
}
<div class="area">1</div>
<div class="area">2</div>
<div class="area">3</div>
<div class="area">4</div>

https://jsfiddle.net/rbw8dpsb/1/

like image 944
user5857398 Avatar asked Mar 07 '23 23:03

user5857398


2 Answers

I advise you to add a container as in your code they are childs of body BUT you don't know the last-child or the first-child of body as you may have other elements like script tags or other tags dynamically added (like in the snippet here or with jsfiddle or any other online coding tools).

.area {
  height: 100px;
  width: 100px;
}

.area:first-child {
  background-color: red;
}

.area:last-child {
  background-color: green;
}
<div>
  <div class="area">1</div>
  <div class="area">2</div>
  <div class="area">3</div>
  <div class="area">4</div>
</div>

Here is a screenshot to show what is inside your body when you run the snippet:

enter image description here

As you may clearly notice, there is a div added at the end which is the last-child of the body. Adding a container will avoid you dealing with random settings and hidden elements added.

like image 149
Temani Afif Avatar answered Apr 06 '23 00:04

Temani Afif


If you don't want to let all that divs in another structure you should use first-of-type and last-of-type instead of first-child and last-child

.area {
  height: 100px;
  width: 100px;
}

.area:first-of-type {
  background-color: red;
}

.area:last-of-type {
  background-color: green;
}
<div class="area">1</div>
<div class="area">2</div>
<div class="area">3</div>
<div class="area">4</div>

As Temani Afif pointed, this solution is arbitrary and may not work in all the situations. As shown, it is not properly working on the code snippet but it does on JSFiddle for example. I.E. https://jsfiddle.net/vm1scerv/

like image 43
Drubio Avatar answered Apr 05 '23 22:04

Drubio