在这篇博客中,我会结合具体例子来分析伪类选择器(可能概念性不是很强,但是好用 ~ )
n=2 选择第二个孩子 n 可以是关键字:even偶数,odd奇数 n 可以是公式, 例如ul li:nth-child(n) 意思是从第0个孩子开始(但是注意 第0个孩子是不存在的),逐次加1,选中所有的 例如ul li:nth-child(2n+1) 意思是n从0开始,选中序号为2*n+1 的孩子
最后根据我的理解写一下nth-of-type 和 nth-child的区别: 见如下ul p div以及style中的内容
结果是背景颜色是根据nth-of-type改变的 不会因为nth-child改变。
因为nth-child在修改样式的时候,会先给ul中的孩子排序,即p为1,div为2,div为3,然后去看nth-child中的数字,发现第一个孩子是p,然后去找前面需要匹配的标签 (此例中为div),然后会发现匹配的是div,不符合
但是nth-of-type是反过来的,它会先看选中的标签是什么(此例中为div),然后为该div中的孩子排序,然后再去匹配nth-of-type中的数字,看看是选中了div中的第几个孩子 找到了之后修改样式
要结合下面这个例子去看哦!
<!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>
ul div:nth-child(1){
background-color: aquamarine;
}
ul div:nth-of-type(1){
background-color: cornflowerblue;
}
</style>
</head>
<body>
<ul>
<p>第一</p>
<div>第二</div>
<div>第三</div>
</ul>
</body>
</html>
需要注意的是:
content:“”
大家可以多找几个before和after的小例子练习,如下:
第一个非常简单,小小小练习
<!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>
div{
width: 200px;
height: 200px;
background-color: rgb(250, 69, 105);
}
div::before{
content:"www";
width: 50px;
height: 50px;
display: block;
/* 记住 是行内元素 要想有盒子 需要有display:block */
background-color: cyan;
}
div::after{
content:"aaa";
width: 50px;
height: 50px;
background-color: darksalmon;
}
</style>
</head>
<body>
<!-- 伪元素选择器
::before 在元素内部的前面插入内容
::after 在元素内部的后面插入内容
注意:
before和after创建的元素属于行内元素
必须要有content属性
-->
<div></div>
</body>
</html>
第二个稍微有难度,效果如下:
大家可以结合代码稍加修改来理解before和after
<!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>
div{
height: 160px;
width: 160px;
position: relative;
background-color:slategrey;
margin: 140px auto;
}
div::before{
content:"";
height: 60px;
width: 60px;
/* position: absolute; */
display: block;
left:0;
top:0;
border-left: 5px solid coral;
border-top: 5px solid coral;
}
div::after{
content:"";
height: 60px;
width: 60px;
position: absolute;
right:0;
bottom:0;
border-right: 5px solid coral;
border-bottom: 5px solid coral;
}
div:hover::before{
transform: rotate(30deg) translate(64px,17px);
transition: 1s;
}
div:hover::after{
transform: rotate(30deg) translate(-66px,-17px);
transition: 1s;
}
</style>
</head>
<body>
<div></div>
</body>
</html>