How can I select the first or the last child with

2019-01-09 18:08发布

问题:

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/

回答1:

I advise you to add a container as in your code they are childs of body and you don't know what is 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:

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.



回答2:

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/