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 正确的第一个或最后一个孩子


基础教程推荐
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- 直接将值设置为滑块 2022-01-01