我们可以用不同的方法选择给定HTML元素的第一个子元素。但是CSS提供了 first-child
属性来选择给定HTML元素的第一个子元素。我们还将学习 nth-child
选择第一个子级。
第一个子语法
第一个子CSS属性语法如下所示。
HTML_ELEMENT:first-child { CSS_CODE;}
- `HTMLu ELEMENT`是我们要选择其第一个子元素的元素类型。
- `:first child`是第一个子级的CSS选择器。
- `CSSu CODE`是我们要应用于给定的第一个子元素的CSS属性。
用第一个子CSS选择第一个子CSS
我们将使用 first-child
给定的HTML元素。我们会将每个第一个孩子的背景色设置为黄色。在本例中,我们将body first元素和div的first elements背景色设置为黄色。
This paragraph is the first child of its parent (body).
This paragraph is not the first child of its parent.
This paragraph is the first child of its parent (div).
This paragraph is not the first child of its parent.
This paragraph is the first child of its parent (div).
This paragraph is not the first child of its parent.
This paragraph is the first child of its parent (div).
This paragraph is not the first child of its parent.

用第n个子CSS选择第一个子CSS
nth-child
是另一个CSS选择器,可用于选择给定HTML元素的第一个子元素。 nth-child()
它的工作原理类似于一个函数,在这个函数中,我们将向第n个子选择器提供子订单号,在本例中,该选择器为1。
This paragraph is the first child of its parent (body).
This paragraph is not the first child of its parent.
This paragraph is the first child of its parent (div).
This paragraph is not the first child of its parent.
This paragraph is the first child of its parent (div).
This paragraph is not the first child of its parent.
This paragraph is the first child of its parent (div).
This paragraph is not the first child of its parent.

选择给定HTML元素的第一个子HTML元素
选择第一个列表项
我们可以使用第一个子项来选择列表的第一项。
- Item 1
- Item 2
- Item 3
- Item 3.1
- Item 3.2
- Item 3.3

选择第一个Div
我们还可以选择HTML元素的第一个div。
First divSecond divThird divFourth divFifth divSixth divSeventh div

用CSS Last Child选择最后一个子HTML元素
CSS还提供 last-child
选择器,它将选择给定HTML元素的最后一个子元素并应用给定的CSS。
First divSecond divThird divFourth divFifth divSixth divSeventh div

相关文章: CSS:n子元素选择器