目录
2.2 nth-child(n)和nth-of-child(n)区别
- 新增css3特性有兼容性问题,ie9以上支持
- 移动端支持优于pc端
一、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元素 |
代码演示:
<!-- disabled禁用按钮 -->
<button disabled="disabled">按钮</button>
<button>按钮</button>
<input type="text" name="" id="" value="文本框"/>
<input type="submit" name="" id="" value="提交"/>
<input type="password" name="" id="" />
<div class="icon1"></div>
<div class="icon2"></div>
/*根据属性的不同选择元素*/
button[disabled]{
cursor:pointer;
}
input[name]{
color:pink;
}
/*根据相同属性的不同属性值选择元素*/
input[type="text"] {
color:red;
}
/*选择div 具有class属性以icon开头的元素*/
div[class^="icon"]{
}
二、结构伪类选择器
根据文档结构来选择元素,常用于根据父元素选择器里面的子元素
亲兄弟才能使用
选择符 | 简介 |
---|---|
E:first-child | 匹配父元素中的第一个子元素E |
E:last-child | 匹配父元素中的最后一个子元素E |
E:nth-child(n) | 匹配父元素中的第n个子元素E |
E:first-of-type | 指定类型E的第一个 |
E:last-of-type | 指定类型E的最后一个 |
E:nth-of-type(n) | 指定类型E的第n个 |
代码演示:
/*选取父元素ul的第一个子元素li*/
li:first-child{
background-color:pink;
}
/*选取父元素ul的第4个子元素li*/
li:nth-child(4){
color:blue;
}
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
2.1nth-child (n)
-
n可以是数字、关键字和公式
-
n如果是数字,就是选择第几个
-
常见的关键词有even偶数、odd奇数
代码演示:
/*选取偶数*/
li:nth-child(even){
color:blue;
}
/*选取奇数*/
li:nth-child(odd){
color:hotpink;
}
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
- 常见的公式如下(如果n是公式,则从0开始计算)
公式 | 取值 |
---|---|
2n | 偶数 |
2n+1 | 奇数 |
5n | 5,10,15…… |
n+5 | 5,6,7,8……(从第5个开始包含第5个到最后) |
-n+5 | 前5个(包含第5个) |
- 第0个元素或者超出了元素的个数会被忽略(相当于其将0计算进去,忽略0这个值)
2.2 nth-child(n)和nth-of-child(n)区别
1.nth-child:只选里面的第几个孩子不管孩子类型;
代码演示:
/*选取div里面的第一个孩子p*/
div :nth-child(1){
color:yellow;
}
/*选取div里面的第二个孩子span*/
div :nth-child(2){
color:blue;
}
/*这种情况一个都不选。因为需要是span又需要是div的第一个孩子*/
/*而span为div的第2个孩子*/
div span:nth-child(1){
color:pink;
}
/*这样则会选择div中的第一个span元素*/
div span:nth-child(2){
color:pink;
}
<div>
<p>
我是一个小小鸟
</p>
<span></span>
<span></span>
<span></span>
</div>
总结: nth-child(n) 选择父元素里面的第n个孩子,不管里面孩子是否是同一个类型
2.nth-of-type(n): 选择指定孩子类型的元素
/*选择div中类型为span的第一个span孩子*/
div span:first-of-type{
color:red;
}
/*选择div中孩子span的第2个span元素 */
div span:nth-of-type(2){
color:red;
}
<div>
<p>
我是一个小熊
</p>
<span></span>
<span></span>
<span></span>
</div>
三、伪元素选择器
选择符 | 简介 |
---|---|
::before | 在元素内部的前面插入内容 |
::after | 在元素内部的后面插入内容 |
注意:
-
before和after必须有content属性
-
before在内容的前面,after在内容的后面
-
before和after创建一个元素,但是属于行内元素,想要加宽高,需要将行内元素转化为块级元素
代码表示:
div{
width:200px;
height:200px;
border:1px solid #000;
}
/*创建的为行内元素想要设宽高需要转化为块元素*/
div::before{
display:block;
content:"我";
width:100px;
height:100px;
background-color:pink;
}