Skip to content

CSS 选择器

选择器优先级

  • important! > 行内样式 > id > class > tag > * > 继承 > 浏览器默认属性
  • 优先级相同时,后出现的样式会覆盖前面的样式
  • 继承的属性优先级最低

Css选择器的解析规则

CSS 选择器是从右向左解析,这样能更早的过滤掉一些无用规则。

选择器

以下列举一些常用到选择器,有些日常业务中不常用,但组件库中较常使用。

选择器版本示例说明
**通配符,选择所有,影响性能
elementp选择所有该标签,不常用
#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]
::beforecss3
::aftercss3
:checked
:disabled
:emptycss3
:enabled
:focus
:hover
:not(selector)css3
:first-of-typecss3p:first-of-type选择其父元素的首个p元素
:last-of-typecss3
:last-childcss3
:nth-child(n)css3选择其父元素的第二个子元素的每个 p 元素。
:nth-last-child(n)css3
:nth-of-type(n)css3其父元素的特定类型的第 n 个子元素的每个元素
:nth-last-of-type(n)css3
:placeholdercss3更改 input 等默认文字样式
:rootcss3文档根元素,一般 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)