CSS3新特性选择器

598 阅读2分钟

IE9以上版本适用
1、属性选择器

image.png

//必须是input,并且包含value这个属性 
input[value] {
    color:pink
}
//只选择type=text 文本框的input
input[type=text] {
     color:pink;
 }
 //首先是div,然后具有class属性,并且属性值必须是icon开头的这些元素
 div[class^=icon] {
    color:red;
 }
 //以data结尾的section元素
 section[class$=data] {
     color: blue;
 }

2、结构伪类选择器

image.png

image.png

//1、选择ul里面的第一个孩子小li  
ul li:first-child {
    background-color: pink;
}
//选择ul里面的第2个孩子小li
ul li:nth-child(2) {
    background-color: pink;
}
//把所有偶数的孩子选出来
ul li:nth-child(even) {
    background-color:grey;
}
//nth-child(n) 从0开始,每次加1,往后面计算,这里必须是n,不能是其他的字母,选择了所有的孩子  
ol li:nth-child(n) {
    beckground-color:pink;
}
//nth-child(2n),从0开始,选择了所有的偶数孩子
ol li:nth-child(2n) {
    beckground-color:pink;
}
//nth-child(2n),选择了所有的奇数孩子
ol li:nth-child(2n+1) {
    beckground-color:pink;
}

image.png
nth-of-type与nth-child的区别

//nth-child 会把所有的孩子都排列序号,序号是固定的
//下面执行的时候首先看:nth-child(1)找到第一个孩子,然后再看前面的div,发现不匹配,所有不会选出来
css部分:
section div:nth-child(1) {
    background-color:blue
 }
 //nth-of-type会把指定元素的盒子排列序号(权重12)
 //执行的时候首先看 div是指定元素,之后再回去看nth-of-type(1)是第几个孩子,所以会选出熊大
 section div:nth-of-type(1) {
     background-color:blue;
 }
 html部分
 <section>
     <p>光头强</p>
     <div>熊大</div>
     <div>熊二</div>
 </section>
 

image.png 3、伪元素选择器

image.png

//父盒子里面的前面
div::before {    //权重是2
    content: '我';   //content是必须写的
}
//父盒子里面的后面
div::after {
    content:'小猪佩奇'
}

伪元素使用场景: 1、伪元素字体图标
2、通过::before实现图片遮罩
3、伪元素清除浮动