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)
我建议你添加一个容器在你的代码,他们是孩子的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;
}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-child的body。添加容器将避免您处理随机设置和添加的隐藏元素。