属性选择器CSS3中给了我们更多的选择器让我们来获取元素,极大程度提高了查找元素的精度以及准确性,值得庆幸的是绝大多数的选择器的语法跟jQuery中兼容
属性选择器的作用就是,根据标签的属性去筛选对应的元素,属性选择器从CSS2推出,在CSS3中增加了几个新的
选择器语法:
下列的属性名都为att 这里就不单独写了 E[att]:包含attr属性 E[att="val"]:属性值为val E[att~="val"]:属性值使用空格进行分割,有一个为val E[att^="val"]:属性值以val开头 E[att$="val"]:属性值以val结尾 E[att*="val"]:属性中包含val E[att|="val"]:属性以‘-’分割,其中有val值(如果属性只有val 那么也会被选中哦)
示例代码:
示例代码直接新建页面,运行即可
兄弟选择器document li[skill]{ background-color: red; } li[color = "white"]{ background-color: blue; } li[color~="red"]{ background-color: orange; } li[color^="bla"]{ border: 10px solid #0094ff; } li[color$="ge"]{ font-size: 32px; } li[color*="orange"]{ color:orange; } li[color|="black"]{ background-color: black; }
- 葫芦娃
- 黑猫警长
- 海尔兄弟
- 舒克和贝塔
- 喜羊羊与灰太狼
- 大头儿子小头爸爸
兄弟选择器的作用是,选择相邻的兄弟节点
语法:
相同父元素中
在选择器1之后
的所有满足选择器2的元素
选择器1~选择器2
示例代码:
在class为.first之后的所有class为.meat的元素背景颜色会变为红色
需要注意的是,之前的并不会获取到哦
伪类选择器兄弟选择器 .first~.meat{ background-color: red; } 牛肉
我是h1
西兰花
西葫芦
牛肉
我是h1小白菜
牛肉
牛肉
伪类选择器,CSS3中推出了一些新的伪类选择器,将常用的列举如下
语法:
使用注意:
* 标签E,必须是某个元素的子元素(在界面上)
* 如果通过伪类选择器找到的元素不是E则选择无效
结构伪类E:first-child:第一个子元素E:last-child:最后一个子元素E:nth-child(n): 第n个子元素,计算方法是E元素的全部兄弟元素;E:nth-last-child(n): 跟E:nth-child(n)类似 ,只是倒着计算; 其中n的取值范围是:0,1,2,3,4...线性累加 可以传入表达式,比如2n,2n+1等等 可以传入特殊字符:even(偶数) odd(奇数)E:empty 指的是E标签,并且内容为空E:not(选择器):指的是,不满足括号内选择器条件的元素E目标伪类E:target:选中当前锚点
示例代码:
示例代码直接新建页面,运行即可
选择器 - 伪类 body { margin: 0; padding: 0; background-color: #F7F7F7; } ul { width: 560px; padding: 0; margin: 100px auto; list-style: none; border-right: 1px solid #CCC; border-bottom: 1px solid #CCC; overflow: hidden; } li { width: 79px; height: 80px; text-align: center; line-height: 80px; border-left: 1px solid #CCC; border-top: 1px solid #CCC; background-color: #FFF; font-size: 24px; font-weight: bold; color: #333; float: left; } li:first-child{ color: red; } li:last-child{ color:red; } li:nth-child(2){ color:blue; } li:nth-child(2n){ color: blue; } li:nth-child(2n+1){ color:red; } li:nth-last-child(1){ background-color: pink; } li:nth-last-child(2){ background-color: yellow; } li:nth-child(odd){ background-color: pink; } li:nth-child(even){ background-color: skyblue; }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
calendar.png
伪元素选择器before&after语法:
使用注意:
需要配合content属性使用(如果没有,输入""空字符串)
可以用来制作图标
部分图标框架使用的就是这种机制
默认是行内元素,根据需求可能需要修
E:before:在元素E之前添加E:after:在元素E末尾添加 也可以写为E::beforeE::afterfirst-letter
语法:
获取的是内容的第一个文字
根据语言不通,会有细微差别
E:first-letter等价于E::first-letterfirst-line
语法:
获取的是内容的第一行的内容
可以配合p标签使用
E:first-line等价于E::first-line
作者:Rella7
链接:https://www.jianshu.com/p/b750c9eb6123



