我想选择第一与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-child
或first-child
的body
,因为你可能有其它元素,如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
。 添加容器将避免你处理随机设置并添加隐藏要素。
如果你不想让其他结构所有的div你应该使用first-of-type
和last-of-type
,而不是first-child
和last-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/