如何选择CSS正确的第一个或最后一个孩子?

use*_*398 4 html css css-selectors

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

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

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

.area:last-child {
  background-color: green;
}
Run Code Online (Sandbox Code Playgroud)
<div class="area">1</div>
<div class="area">2</div>
<div class="area">3</div>
<div class="area">4</div>
Run Code Online (Sandbox Code Playgroud)

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

Tem*_*fif 5

我建议你添加一个容器在你的代码,他们是孩子的body,你不知道什么是last-childfirst-childbody,你可能有其他元素,如script动态地添加标签或其他标记(如在这里摘录或的jsfiddle或任何其他在线编码工具)

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

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

.area:last-child {
  background-color: green;
}
Run Code Online (Sandbox Code Playgroud)
<div>
  <div class="area">1</div>
  <div class="area">2</div>
  <div class="area">3</div>
  <div class="area">4</div>
</div>
Run Code Online (Sandbox Code Playgroud)

这是一个截图,显示了运行代码段时体内的内容:

在此处输入图片说明

正如你可以清楚地看到,有一div处是最后增加 last-childbody。添加容器将避免您处理随机设置和添加的隐藏元素。

  • ...我也相信OP对类,子类和类型元素选择器感到困惑。 (2认同)