如何选择第一个或最后一个孩子与CSS正确吗?如何选择第一个或最后一个孩子与CSS正确吗?(How c

2019-05-12 11:08发布

我想选择第一与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/

Answer 1:

我建议你在你的代码,他们是孩子的添加一个容器body ,你不知道什么是last-childfirst-childbody ,因为你可能有其它元素,如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> 

下面是截图显示的是你的身体内部,当你运行该代码片段:

正如你可以清楚地看到,有一个div加在它结束last-child的的body 。 添加容器将避免你处理随机设置并添加隐藏要素。



Answer 2:

如果你不想让其他结构所有的div你应该使用first-of-typelast-of-type ,而不是first-childlast-child

 .area { height: 100px; width: 100px; } .area:first-of-type { background-color: red; } .area:last-of-type { background-color: green; } 
 <div class="area">1</div> <div class="area">2</div> <div class="area">3</div> <div class="area">4</div> 

由于毯螅阿菲夫指出,这种解决方案是任意的,可能无法在所有的情况下工作。 如图所示,这是不正常的代码片段,但它确实对的jsfiddle例如。 IE https://jsfiddle.net/vm1scerv/



文章来源: How can I select the first or the last child with CSS correct?