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

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

问题描述

我希望使用CSS选择第一个和最后一个子级,但它不起作用。请看一下我的小提琴,帮帮我:

.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/

推荐答案

我建议您添加一个容器,因为在您的代码中它们是body的子级,但您不知道last-childfirst-childfirst-child,因为您可能有其他元素,如script标签或其他动态添加的标签(如此处的代码片段或使用jsfiddle或任何其他在线编码工具)。

.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>

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

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

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

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