How can I select the first or the last child with CSS correct?(如何正确选择 CSS 正确的第一个或最后一个孩子?)
问题描述
我想用 CSS 选择第一个和最后一个孩子,但它不起作用.请看看我的小提琴并帮助我:
.area {高度:100px;宽度:100px;}.area:first-child {背景颜色:红色;}.area:last-child {背景颜色:绿色;}
<div class="area">1</div><div class="area">2</div><div class="area">3</div><div class="area">4</div>
您可能清楚地注意到,在 body 的 the
last-child
末尾添加了一个 div
代码>.添加容器将避免您处理随机设置和添加的隐藏元素.
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
BUT you don't know the last-child
or the first-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
. Adding a container will avoid you dealing with random settings and hidden elements added.
这篇关于如何正确选择 CSS 正确的第一个或最后一个孩子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何正确选择 CSS 正确的第一个或最后一个孩子


- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 400或500级别的HTTP响应 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01