在css中,有两种伪类选择器设置指定孩子样式方法,两者区别是什么?
一、两者都可以实现的情况;
首先对于nth-child和nth-of-type都可以执行的情况 我们举个例子。
如果是写ul>li的写法,我们发现会两者都能实现
nth-child代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
ul li:nth-child(1){
color:green;
}
</style>
</head>
<body>
<ul>
<li>Hello1</li>
<li>Hello2</li>
<li>Hello3</li>
<li>Hello4</li>
<li>Hello5</li>
<li>Hello6</li>
</ul>
</body>
</html>
结果:
nth-of-type代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
ul li:nth-of-type(1){
color:red;
}
</style>
</head>
<body>
<ul>
<li>Hello1</li>
<li>Hello2</li>
<li>Hello3</li>
<li>Hello4</li>
<li>Hello5</li>
<li>Hello6</li>
</ul>
</body>
</html>
结果:
发现在ul>li下都可以匹配到。再来说说区别
二、两者的区别
对于nth-child:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.box div:nth-child(1){
color:red;
}
</style>
</head>
<body>
<div class="box">
<p>你猜猜我会变色吗</p>
<div>我要变成红色</div>
<div>我不会变颜色</div>
</div>
</body>
</html>
结果:
对于nth-of-type:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.box div:nth-of-type(1){
color:red;
}
</style>
</head>
<body>
<div class="box">
<p>你猜猜我会变色吗</p>
<div>我要变成红色</div>
<div>我不会变颜色</div>
</div>
</body>
</html>
结果:
在上面两种情况下,由于div:nth-child(1)是先寻找第一个孩子,发现是p标签,然后在去寻找div,发现不匹配,所以没有变色。
div:nth-of-type(1) 是先去寻找div标签,然后再去找第一个div,所以匹配到,变成了红色。