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

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

问题描述

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

.area {height :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 ,你不知道什么是 body 的最后一个子元素,因为你可能有其他元素如脚本标签或其他标签动态添加(就像这里的代码片段或者jsfiddle或者其他在线编码工具一样)

  .area {height: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>  

下面是一个屏幕截图,用于显示运行代码段时身体内部的内容: stack.imgur.com/LL25t.pngrel =nofollow noreferrer>



正如您可能已经清楚注意到的那样,最后添加了 div body 的最后一个孩子


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 and you don't know what is the last 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.

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

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