文章目录
以下选择器都为C3的选择器
示例代码:
<div>
<ul>
<li><a href="">第1个a标签</a></li>
<a href="">第1个盒子外a标签</a>
<li><a href="">第2个a标签</a></li>
<a href="">第2个盒子外a标签</a>
<li><a href="">第3个a标签</a></li>
<li><a href="">第4个a标签</a></li>
<li><a href="">第5个a标签</a></li>
<li><a href="">第6个a标签</a></li>
</ul>
</div>
网页样式:
基础篇
:nth-child(n)选择器
示例1
- 选择的对象: 父盒子下的第n个子元素
li标签的父元素(ul)的第一个子元素
li:nth-child(1){
background-color: red;
}
示例2
- tip:一定要看父盒子是谁,不能只看子元素
a标签的父元素是li,也就是li标签下的第1个子元素
但是ul也是a的父元素,所以ul下的第1个子元素,再次把第1个li标签选中了
a:nth-child(1){
background-color: red;
}
示例3
- 前面的li标签起到过滤作用
选择li标签的父元素(ul)下的第二个子元素,然后进行判断:
if(是li标签){
选择
}else{
我拒绝选择
}
比如这个例子父元素的第二个元素不是li标签,是a标签,则不选择
li:nth-child(2){
background-color: red;
}
p:nth-of-type(n)选择器
示例4
- 选择的对象: 父盒子下的第n个p标签(p标签可以改为任意标签或者其他选择器)
选择li标签的父盒子(ul)下的第一个li标签
li:nth-of-type(1){
background-color: red;
}
示例5
- tip:同样一定要看父盒子
选择a标签父盒子(li)下的第一个a标签
同时a标签的父盒子还有(ul),所以ul下的第一个a标签也被选中
a:nth-of-type(1){
background-color: red;
}
进阶篇
:nth-child(表达式) 和 nth-type-of(表达式)选择器
- 选择的对象: 父盒子下的第(表达式)个子元素
- 表达式个子元素???这是啥意思呢???
- 表达式可以写有关n的表达式 {n从0开始} (如:(2n-1),(2n),(3n+1),(-n+5),(n-3)等)
- 一定注意: 表达式中必须是(an+b)这样的表达式, 不满足交换律 且 (参数a,b为正负整数)
示例6
但是
nth-child有过滤机制,不为li标签的子标签就不选择了,但是不满足的标签仍占有一个位置
而nth-type-of没有过滤,如果不为li标签的子标签直接跳过,不满足的标签不占有位置
说了这么多,还是来个栗子比较明白[手动狗头]
选择元素: 选择前3个li标签
非li标签直接跳过
li:nth-of-type(-n+3){
background-color: red;
}
选择元素: 选择前3个li标签,由于第二个子标签不是li标签,所以就没选
但是
第二个标签仍然占着位置
li:nth-child(-n+3){
background-color: red;
}
- 说了这么多,我常用的还是:nth-type-of(),因为不用考虑过滤和占位问题
- 下面附上几个常用的表达式
示例7
//{n从0开始}//
选择全部li标签
li:nth-type-of(n)
选择前x个li标签
li:nth-type-of(-n+x)
选择x到最后一个li标签
li:nth-type-of(n+x)
选择奇数位的li标签
li:nth-type-of(2n+1)
li:nth-type-of(odd)
选择偶数位的li标签
li:nth-type-of(2n)
li:nth-type-of(even)
高阶篇
- 欢迎来到高阶,既然你已经看到了这里,那么相信你对这个选择器有一定了解
- css中的选择器当然不止这一个
- 那么最高境界自然是-----选择器联用(也叫"指哪选哪")主要是和子代选择器联用
- 即 : 在不用class和id选择器的情况下选择出任何一个元素
当然class和id选择器是非常重要的, 因为名字直观的特点, 也是我平时用的最多的选择器, 这里只是当做练习整点活,
做正式项目的时候还是要以可读性为最高优先级
示例8
- 比如以下这个布局
<div>
<div>
<div>1</div>
</div>
<div>
<div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
<div>
<div>5</div>
</div>
</div>
</div>
- 在不用class和id选择器的情况下选择出任何一个元素
/* 1 */
body>div>div:nth-of-type(1)>div:nth-child(1){
background-color: red;
}
/* 2 */
body>div>div>div:nth-of-type(1)>div:nth-of-type(1){
background-color: red;
}
/* 3 */
body>div>div>div:nth-of-type(1)>div:nth-of-type(2){
background-color: red;
}
/* 4 */
body>div>div>div:nth-of-type(1)>div:nth-of-type(3){
background-color: red;
}
/* 5 */
body>div>div>div:nth-of-type(2)>div:nth-of-type(1){
background-color: red;
}