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

:first-child (匹配父元素的第一个子元素)

:first-of-type (匹配父元素的相同子元素的第一个子元素)

这里还要区分是元素选择器还是非元素选择器

下面假设用来举例的元素是p,类名为pclass

例如 :

1、:first-child 

p:first-child 匹配p标签的父元素的第一个子元素并且这个子元素必须为p标签

.pclass:first-child 匹配类为pclass的p标签的父元素的第一个子元素并且这个子元素必须类为pclass的p标签

first-child匹配上的情况

1)p:first-child       p元素是父元素的第一个子元素

2).pclass:first-child        类为pclass的p元素是父元素的第一个子元素

first-child 匹配不上的情况

1)、父元素第一个子元素不是p标签

<style> 
p:first-child
{
	background:#ff0000;
}
</style>
</head>
<body>
<h1>这是一个标题</h1>
<p>这是第一个段落。</p>
<p>这是第二个段落。</p>
</body>

运行结果

2)、父元素的第一个子元素类不为pclass

<style> 
.pclass:first-child
{
	background:#ff0000;
}
</style>
</head>
<body>
<p>这是第一个段落。</p>
<p class="pclass">这是第二个段落。</p>
</body>

运行结果:

2、:first-of-type

p:first-of-type匹配父元素的子元素中的第一个p元素(不管这个p是不是父元素的第一个子元素)

.pclass:first-of-type匹配父元素的子元素中的第一个类为pclass的元素(可以匹配多个,如果有多个类为pclass的不同标签的子元素)


:first-of-type匹配上的情况:

1)pclass对应的p元素是父元素的第一个p元素

<style> 
.pclass:first-of-type
{
	background:#ff0000;
}
</style>
</head>
<body>
<h1>这是一个标题</h1>
<p class="pclass">这是第一个段落。</p>
<p>这是第二个段落。</p>
</body>

运行结果:

2)匹配所有类为pclass的不同元素的第一个元素

<style> 
.pclass:first-of-type
{
	background:#ff0000;
}
</style>
</head>
<body>
<h1 class="pclass">这是一个标题</h1>
<p class="pclass">这是第一个段落。</p>
<p>这是第二个段落。</p>
</body>

运行结果:

:first-of-type匹配不上的情况

1)pclass对应的p元素不是父元素的第一个p元素

<style> 
.pclass:first-of-type
{
	background:#ff0000;
}
</style>
</head>
<body>
<h1>这是一个标题</h1>
<p>这是第一个段落。</p>
<p class="pclass">这是第二个段落。</p>
</body>

猜你喜欢

转载自blog.csdn.net/zhongmei121/article/details/105101995