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

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.

Leave a Comment