Skip to content

CSS选择器的优先级顺序是怎样的呢? #25

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
JCHappytime opened this issue Mar 4, 2021 · 0 comments
Open

CSS选择器的优先级顺序是怎样的呢? #25

JCHappytime opened this issue Mar 4, 2021 · 0 comments
Labels
CSS 样式相关问题

Comments

@JCHappytime
Copy link
Owner

JCHappytime commented Mar 4, 2021

前言

在我们日常编写CSS的时候,都会有一个疑惑就是:CSS选择器的优先级问题。我们先来看一小段代码:

.text-size {
  font-size: 15px !important;
}

这个时候,!important是具有最高优先级的,而且相比较内联的样式而言,它的优先级会更高。那么除了!important之外的其他选择器呢?

CSS选择器

我们把选择器的名称以及权重列出来看一下。

选择器名称 权重
内联样式 1000
ID选择器 100
类选择器(包括属性选择器和伪类) 10
标签和伪元素选择器 1
组合符和通配符 0

根据表中给出来的权重值,对于我们在编写CSS的时候就会有一个比较明确的顺序了:

.text-box > span {
  height: 100px;    // 权重值=10+1=11(类选择器+标签)
}

.text-box span:last-child {
  font-size: 18px;   // 权重值=10+10+1=21(类选择器+伪类+伪元素选择器)
}

.text-box div>span:first-child {
  color: red;   // 权重值=10+10+1+1=22(类选择器+标签+标签+伪元素选择器)
}
@JCHappytime JCHappytime added the CSS 样式相关问题 label Mar 4, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
CSS 样式相关问题
Projects
None yet
Development

No branches or pull requests

1 participant