CSS 选择器
选择器优先级
important!> 行内样式 >id>class>tag> * > 继承 > 浏览器默认属性- 优先级相同时,后出现的样式会覆盖前面的样式
- 继承的属性优先级最低
Css选择器的解析规则
CSS 选择器是从右向左解析,这样能更早的过滤掉一些无用规则。
选择器
以下列举一些常用到选择器,有些日常业务中不常用,但组件库中较常使用。
| 选择器 | 版本 | 示例 | 说明 |
|---|---|---|---|
| * | * | 通配符,选择所有,影响性能 | |
| element | p | 选择所有该标签,不常用 | |
| #id | #header | 全局唯一 | |
| .class | .name | ||
| .class1.class2 | .name1.name2 | 同时存在着两个选择器 | |
| .class1, class2 | .name1, .name2 | 对这两个选择器 | |
| .class1 .class2 | |||
| .class1>.class2 | .name1 > .name2 | ||
| .class1+.class2 | 组件中比如按钮组设置右外边距常用 | ||
| .class1~.class2 | |||
| [attribute] | |||
| [attribute=value] | |||
| [attribute~=value] | |||
| [attribute|=value] | |||
| [attribute^=value] | |||
| [attribute$=value] | a[href$=".pdf"] | ||
| [attribute*=value] | |||
| ::before | css3 | ||
| ::after | css3 | ||
| :checked | |||
| :disabled | |||
| :empty | css3 | ||
| :enabled | |||
| :focus | |||
| :hover | |||
| :not(selector) | css3 | ||
| :first-of-type | css3 | p:first-of-type | 选择其父元素的首个p元素 |
| :last-of-type | css3 | ||
| :last-child | css3 | ||
| :nth-child(n) | css3 | 选择其父元素的第二个子元素的每个 p 元素。 | |
| :nth-last-child(n) | css3 | ||
| :nth-of-type(n) | css3 | 其父元素的特定类型的第 n 个子元素的每个元素 | |
| :nth-last-of-type(n) | css3 | ||
| :placeholder | css3 | 更改 input 等默认文字样式 | |
| :root | css3 | 文档根元素,一般 var 定义全局变量使用 |
问题
1. 如何使用一个元素实现如下功能?
伪元素的应用
2. first-of-type nth-child(n) nth-of-type(n) 的区别?
:first-of-type其父元素的首个元素:nth-child(n)其父元素的第 n 个子元素,不论元素的类型:nth-of-type(n)其父元素的特定类型的第 n 个子元素的每个元素
:first-of-type 等同于 :nth-of-type(1)
前端知识点