first-child和first-of-type的区别

:first-child和:first-of-type的作用和区别

  • :first-child:定义父元素下第一个元素的样式。
    例子:.box>h1:first-child{}:定义.box下第一个子元素为h1的样式,如果第一个子元素不是h1则没有样式显示
  • first-of-type:定义父元素下同一类元素中的第一个元素的样式。
    例子:.box>h1:first-of-type{}:对.box下所有的h1子元素当中的第一个h1元素定义样式

运行如下代码,解析下输出样式的原因。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
> <!DOCTYPE html>
> <html>
> <head>
> <meta charset="utf-8">
> <title>first-child vs first-of-child</title>
> <style>
> /*选中.item1,该元素是它父亲下 当前类型的 第一个孩子*/
> .item1:first-of-type{
> background: red;
> }
>
> /*选中.item1,该元素是它父亲所有的 .item1孩子中的第一个*/
> .item1:first-child{
> color: blue;
> }
>
> </style>
> </head>
> <body>
>
> <!--红色,因为该元素是item1,且是它父亲的孩子中,div类型下的第一个-->
> <!--蓝色,因为该元素是item1,且是它父亲的孩子中的第一个-->
> <div class="item1">111</div>
>
> <div class="ct">
>
> <!--蓝色,因为该元素是item1,且是它父亲的孩子中的第一个-->
> <!--红色,因为该元素是item1,且是它父亲的孩子中,p 类型下的第一个-->
> <p class="item1">222</p>
>
> <!--红色,因为该元素是item1,且是它父亲的孩子中,div 类型下的第一个-->
> <div class="item1">333</div>
> <div class="item1">444</div>
> <div class="item2">
>
> <!--蓝色,因为该元素是item1,且是它父亲的孩子中的第一个-->
> <!--红色,因为该元素是item1,且是它父亲的孩子中,div 类型下的第一个-->
> <div class="item1">555</div>
>
> <div class="item1">666</div>
> </div>
> </div>
> </body>
> </html>
  • .item1:first-of-type{background: red; }:所有子元素中class=“item1”且为同类型元素当中的第一个元素。
    • “111”是body下class=“item1”且为div类型的子元素中的第一个元素。
    • “222”是< div class=”ct”>下class=“item1”且为p类型的子元素中的第一个元素。
    • “333”是< div class=”ct”>下class=“item1”且为div类型的子元素中的第一个元素。
    • “555”是< div class=”item2”>下class=“item1”且为div类型的子元素中的第一个元素
  • .item1:first-child{color: blue;}:所有子元素中class=”item1”中的第一个元素。
    • “111”是body下class=“item1”的子元素中的第一个元素。
    • “222”是< div class=”ct”>下class=“item1”的子元素中的第一个元素。
    • “555”是< div class=”item2”>下class=“item1”的子元素中的第一个元素。

text-align: center的作用是什么,作用在什么元素上?能让什么元素水平居中.

  • 设置文本内容或行内元素水平居中,作用在块级元素中的行内元素上,让其水平居中
文章目录
  1. 1. :first-child和:first-of-type的作用和区别
  2. 2. 运行如下代码,解析下输出样式的原因。
  3. 3. text-align: center的作用是什么,作用在什么元素上?能让什么元素水平居中.
,