CSS选择器总结
优先级
!important > 行间样式 > id > class、属性 伪类 > 通配符
/* !important */
background-color: skyblue !important;
/* 行内样式 */
<div class="out" style="background-color: yellow;">
/* 通配符(星号) */
* { color : red; }
!important 可以把优先级提至最高,就是因为它的优先级最高,所以需要谨慎使用它,以下有些使用注意事项:
- 一定要优先考虑使用样式规则的优先级来解决问题而不是 !important;
- 只有在需要覆盖全站或外部 CSS 的特定页面中使用 !important;
- 永远不要在全站范围的 CSS 代码中使用 !important;
基础选择器
- 标签选择器:div、a、h1
- 类选择器:.checked
- ID 选择器:#picker
- 通配选择器:*
a标签的伪类选择器
| 选择器 | 示例 | 注释 |
|---|---|---|
| :link | a:link | 鼠标不放上去,也不做任何操作时 |
| :visited | a:visited | 已被访问过的链接 |
| :active | a:active | 鼠标按下链接时产生变化 |
| :hover | a:hover | 鼠标放上去的时候产生变化 |
tip:a标签点击跳转时不同的操作 target="_self"/"_blank" 的使用
<a href="http://www.w3school.com.cn" target="_blank">W3Sschool</a>
// 打开一个新页面跳转
<a href="http://www.w3school.com.cn" target="_self">W3Sschool</a>
// 在该页面跳转
子类选择器
常用
| 选择器 | 示例 | 注释 |
|---|---|---|
| ele > ele | div > p | 子选择器,选择父级是div元素的p元素 |
| ele + ele | div+p | 相邻兄弟选择器,选择紧挨着div元素之后的一个p元素,后面p会被忽略 |
| ele ele | div p | 后代选择器,选择div元素下的全部p元素 |
| ele ~ ele | div ~ p | 普通兄弟选择器,选择div元素之后的所有p元素 |
属性选择器
有点类似与正则的方式
| 选择器 | 示例 | 注释 |
|---|---|---|
| [attr^=val] | a[src^=https] | 属性以指定值开头的元素,选择src属性值以https开头的元素 |
| [attr=val] | [target=_blank] | 属性等于指定值的元素,选择有target属性并且属性值是_blank的元素 |
| [attr$=val] | a[src$=.pdf] | 属性以指定值结尾的元素,选择src属性值以.pdf结尾的元素 |
| [attr*=val] | a[src*=demo] | 属性包含指定值的元素,选择src属性的值包含子字符串demo的元素 |
结构伪类选择器
| 选择器 | 示例 | 注释 |
|---|---|---|
| :first-letter | p:first-letter | 元素的首字母,选择每一个p元素的第一个字母 |
| :first-line | p:first-line | 元素的首行,选择每一个p元素的第一行 |
| :nth-child(n) | p:nth-child(2) | 元素中指定顺序索引的元素,选择每个p元素是其父级的第二个子元素 |
| :nth-last-child(n) | p:nth-last-child(2) | 元素中指定逆序索引的元素,选择每个p元素的是其父级的倒数第二个子元素 |
| :first-child | p:first-child | 元素中为首的元素,选择p元素是其父级的第一个子级的元素 |
| :last-child | p:last-child | 元素中为尾的元素,选择每个p元素是其父级的最后一个子元素 |
| :only-child | p:only-child | 父元素仅有该元素的元素,选择每个p元素是其父级的唯一子元素 |
| :nth-of-type(n) | p:nth-of-type(2) | 标签中指定顺序索引的标签,选择每个p元素是其父级的第二个p元素 |
| :nth-last-of-type(n) | p:first-letter | 标签中指定逆序索引的标签,选择每个p元素的是其父级的倒数第二个p元素 |
| :first-of-type | p:first-of-type | 标签中为首的标签,选择每个p元素是其父级的第一个p元素 |
| :last-of-type | p:last-of-type | 标签中为尾标签,选择每个p元素是其父级的最后一个p元素 |
| :only-of-type | p:only-of-type | 父元素仅有该标签的标签,选择每个p元素是其父级的唯一p元素 |
:nth-last-of-type 可以用来奇偶性的选择
- IE 8以及更早版本的浏览器不支持:nth-last-of-type() 选择器
/* HTML代码 */
<style>
p:nth-last-of-type(odd) {
background: #96b97d;
}
p:nth-last-of-type(even) {
background: #00F5A0
}
</style>
<body>
<p>P1</p>
<p>P2</p>
<p>P3</p>
<p>P4</p>
</body>
效果图:
然后 完。
主要给自己一个总结,内容也基本比较偏简洁