一、概念:
- CSS3是CSS(层叠样式表)技术的升级版本,于1999年开始制订,2001年5月23日W3C完成了CSS3的工作草案,主要包括盒子模型、列表模块、超链接方式、语言模块、背景和边框、文字特效、多栏布局等模。
- 要使用css对HTML页面中的元素实现一对一,一对多或者多对一的控制,这就需要用到CSS选择器。
- HTML页面中的元素就是通过CSS选择器进行控制的。
二、css3之前的选择器
- ID选择器(#id名)
- 类选择器(.class名)
- 包含选择器(E F)
- 伪类选择器(:link,visited,hover,active,focus,first-child)
- 伪元素选择器(::first-line,first-letter,before,after)
- 通配选择器(*)
- 属性选择器(foo[name=‘martin’])
- 子包含选择器(E>F)
- 相邻兄弟选择器(E+F)
三、css3新增选择器
新增属性选择器:
1.[foo^=‘bar’] 匹配E元素,该元素包含foo属性,且foo属性值以bar开头
/* 匹配属性值以指定开头的每个元素 */
img[class^='a'] {
border: 5px solid #f00;
}
2.[foo$=‘bar’] 匹配E元素,该元素包含foo属性,且foo属性值以bar结尾
/* 匹配属性值以指定结尾的每个元素 */
img[class$='a'] {
border: 5px solid #ff0;
}
3.[foo*=‘bar’] 匹配E元素,该元素包含foo属性,且foo属性值包含bar字符串
/* 匹配属性值中包含指定值的每个元素 */
img[class*="img"] {
width: 100px;
height: 100px;
}
新增结构伪类选择器:
- root 匹配文档所在的根元素
html:root .test {
color: purple\0;
}
- nth-child(n) 匹配E所在父元素第n个匹配E的元素,非E的子元素也参与排序,若第n个子元素不是E元素,则该语句没有效果(注意这里的n从1开始)
/* 匹配属于其父元素中第n个子元素 子元素相对整洁(没有其他的标签乱入)*/
/* 所有子元素排序 */
.listB li:nth-child(2) {
background-color: #f00;
}
3.nth-last-child(n) 匹配E所在父元素倒数第n个匹配E的元素
/*匹配倒数第一个子元素*/
.listB li:nth-last-child(1) {
background-color: #00f;
}
4.nth-of-type(n) 匹配E所在父元素第n个匹配E的元素,非E的子元素不参与排序(n同样是从1开始)注意区别nth-child(n)
.listB li:nth-of-type(2) {
background-color: #f40;
}
5.last-child
/* 匹配属于父元素中的最后一个 */
.listA li:last-child {
background-color: #ff0;
}
6.first-of-type
/* 匹配属于父元素中的第一个 */
.listA h1:first-child {
background-color: #f00;
}
7.last-of-type
/* 找到ul下面的最后一个子元素 */
.listA h1:last-of-type {
background-color: #ff0;
font-size: 16px;
}
8.only-child
/* 匹配属于其父元素中仅有的一个子元素 */
ul li:only-child {
background-color: #0f0;
color: #999;
font-size: 30px;
}
9.only-of-type
/*匹配父元素的所有子元素中唯一的那个子元素*/
p:only-of-type {
color: #f00;
}
10.empty
/* 匹配没有子元素的元素,也不能包括文本元素 */
ul:empty {
width: 100px;
height: 100px;
background-color: #00f;
}
ps:如何选择选择器要看在项目实战中的情况,以上只是参考