如何正确选择 CSS 正确的第一个或最后一个孩子? [英] How can I select the first or the last child with CSS correct?

查看:26
本文介绍了如何正确选择 CSS 正确的第一个或最后一个孩子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 CSS 选择第一个和最后一个孩子,但它不起作用.请看看我的小提琴并帮助我:

.area {高度:100px;宽度:100px;}.area:first-child {背景颜色:红色;}.area:last-child {背景颜色:绿色;}

<div class="area">1</div><div class="area">2</div><div class="area">3</div><div class="area">4</div>

您可能清楚地注意到,在 body 的 the last-child 末尾添加了一个 div.添加容器将避免您处理随机设置和添加的隐藏元素.

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/

解决方案

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:

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.

这篇关于如何正确选择 CSS 正确的第一个或最后一个孩子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆