博主头像
<CodeEra />

心存敬畏 行有所止

CSS选择器及优先级顺序

CSS(层叠样式表)中有多种选择器,每种选择器都有不同的优先级。优先级决定了当多个样式规则应用于同一个元素时,哪个规则会生效。以下是常见的CSS选择器及其优先级顺序:

1. 通用选择器

  • *
  • 优先级:0

2. 元素选择器

  • div, p, h1, span, a, 等等
  • 优先级:1

3. 类选择器

  • .class
  • 优先级:10

4. 属性选择器

  • [type="text"], [href], [class~="example"], 等等
  • 优先级:10

5. 伪类选择器

  • :hover, :focus, :nth-child(n), :first-child, 等等
  • 优先级:10

6. ID选择器

  • #id
  • 优先级:100

7. 内联样式

  • <div style="color: red;">
  • 优先级:1000

8. !important

  • color: red !important;
  • 优先级:最高,覆盖所有其他规则

优先级计算规则

优先级是一个由四个部分组成的权重值:

  • 内联样式:1,0,0,0
  • ID选择器:0,1,0,0
  • 类选择器、属性选择器、伪类选择器:0,0,1,0
  • 元素选择器、伪元素选择器:0,0,0,1
  • 通用选择器:0,0,0,0

当多个选择器应用于同一个元素时,优先级高的规则会覆盖优先级低的规则。如果优先级相同,则后定义的规则会覆盖先定义的规则。

示例

/* 优先级:0,0,0,1 */
div {
    color: blue;
}

/* 优先级:0,0,1,0 */
.example {
    color: green;
}

/* 优先级:0,1,0,0 */
#unique {
    color: red;
}

/* 优先级:1,0,0,0 */
<div style="color: yellow;">

在这个例子中,#unique 的优先级最高,其次是 .example,然后是 div。如果元素同时有 id="unique"class="example",那么 color: red; 会生效。

总结

  • !important 优先级最高,覆盖所有其他规则。
  • 内联样式 优先级次高。
  • ID选择器 优先级高于类选择器、属性选择器和伪类选择器。
  • 类选择器、属性选择器、伪类选择器 优先级高于元素选择器。
  • 元素选择器 优先级最低。
发表新评论