关系选择器
- 后代选择器:E F 选择E元素的所有后代F元素
- 子选择器:E > F 选择E元素的所有子元素F
- 相邻同胞选择器:E + F 选择紧接在E元素之后的第一个兄弟元素F
- 同胞选择器:E ~ F 选择E元素之后的所有兄弟元素F
nth-child和nth-of-type
区别:
nth-of-type为什么要叫:nth-of-type?因为它是以"type"来区分的。也就是说:ele:nth-of-type(n)是指父元素下第n个ele元素。(标签优先)
而ele:nth-child(n)是指父元素下第n个元素且这个元素为ele,若不是,则选择失败。 (顺序优先)
解释及注意:
标签优先
如果是class那么碰到不同类型标签的,单独分类,符合条件的选中。
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style type="text/css">
.a:nth-of-type(3){
color: red;
}
</style>
</head>
<body>
<p class="a">1</p>
<h1 class="a">2</h1>
<h1 class="a">3</h1>
<h1 class="a">4</h1>
<p class="a">5</p>
<p class="a">6</p>
</body>
</html>
效果:
顺序优先
代码1:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style type="text/css">
.box{
width: 400px;
height: 400px;
background-color: aqua;
}
:nth-child(1){
width: 50px;
height: 50px;
background-color: black;
}
</style>
</head>
<body>
<div class="box">
<div id="a"></div>
<div id="b"></div>
<div id="c"></div>
</div>
</body>
</html>
效果:
图中一片黑,是因为:nth-child()前面没有加限定,name选择html中第一个元素即html
代码二:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style type="text/css">
.box{
width: 400px;
height: 400px;
background-color: aqua;
}
div:nth-child(1){
width: 50px;
height: 50px;
background-color: black;
}
</style>
</head>
<body>
<div class="box">
<div id="a"></div>
<div id="b"></div>
<div id="c"></div>
</div>
</body>
</html>
效果:
我们发现蓝块块没有了!我个人认为是div这只指定不够明确。
那么我们换为
#a:nth-child(1)
效果:
ok有效。所以我们使用nth-child()时,限定词应该尽可能准确
另外当限定词为标签但代码中又匹配不对,比如p:nth-child(3)但代码中第三个标签不是p。这是会发生匹配失败,然后无效
参考文章:
深入理解css3中 nth-child 和 nth-of-type 的区别
CSS3选择器:nth-child和:nth-of-type之间的差异
浅谈nth-child和nth-of-type的区别
彻底理解nth-child和nth-of-type的区别。
关系选择器