一.CSS3新增选择器
属性选择器
- E[att]:具有att属性的E元素
- E[att=val]:具有att属性且值为val的E元素
- E[att^=val]:具有att属性且值以val开头的E元素
- E[att$=val]:具有att属性且值以val结尾的E元素
- E[att*=val]:具有att属性且值包含val的E元素
结构伪类选择器
- E :first-child:选择E元素的第一个子元素
-
- E A:first-child:选择E元素的第一个子元素,且该子元素是A类型元素
- E :last-child:选择E元素的最后第一个子元素
-
- E A:last-child:选择E元素的最后第一个子元素,且该子元素是A类型元素
- E :nth-child(n):选择E元素的指定规则元素,比如 1、2、3这样的数字,even(偶数)、odd(基数)这样的关键字,n或者2n+1这样的表达式
-
- E A:nth-child(n):选择E元素中符合指定规则的子元素,且该子元素是A类型的元素
- E :first-of-type:选择E元素中不同类型的子元素中的第一个
-
- E A:first-of-type:选择E元素中子元素为A,A元素中的第一个
- E :last-of-type:选择E元素中不同类型的子元素中的最后一个
-
- E A:last-of-type:选择E元素中子元素为A,A元素中的最后一个
- E :nth-of-type(n):选择E元素的不同类型的指定规则
-
- E A:nth-of-type:选择E元素中子元素为A,A元素的指定规则
伪元素选择器
- ::before:在元素前面插入内容
- ::after:在元素后面插入内容
示例:使用::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 {
position: relative;
width: 200px;
height: 200px;
margin-right: 60px;
}
img {
width: 100%;
height: 100%;
}
div::after {
display: none;
position: absolute;
top: 0;
left: 0;
content: '';
width: 100%;
height: 100%;
background: url(./src/broadcast.png) rgba(0, 0, 0, .5) center center no-repeat
}
div:hover::after {
display: block;
}
</style>
</head>
<body>
<div>
<img src="./src/pig.jpg">
</div>
</body>
</html>
二.nth-child和nth-of-type的区别
区别
nth-child(n)选中的是当前元素的父元素下的所有元素的第n个
nth-of-type(n)选择的是当前元素的父元素下的所有元素的每一种标签的第n个(每种tagName都会选中,如果有的话)
示例
<!DOCTYPE html>
<html>
<head>
<style>
.a:nth-of-type(4) {
background: red;
}
.a:nth-child(4) {
background: green;
}
</style>
</head>
<body>
<h1>这是标题</h1>
<div class="a">div1</div>
<p>p1特别</p>
<label class="a">label1</label>
<div>div2特别</div>
<div>div2特别的</div>
<div class="a">div3</div>
<p class="a">p2</p>
<label class="a">label2</label>
<div class="a">div4</div>
<p class="a">p3</p>
<label>label3特别</label>
<div class="a">div5</div>
<p class="a">p4</p>
<label class="a">label4</label>
</body>
</html>
结果分析
.a:nth-of-type(4):选中了div,p和label标签中的第四个并标红
.a:nth-child(4):选中了所有子元素的第四个并标绿
除此之外还要求这些被选中的标签有class=“a”,如果没有,则既不会选择当前元素,也不会选中下一个有class="a"的元素