js css html

选择器的优先级

2023-02-10  本文已影响0人  Cissy_fba3

选择器可以分为 0-5 6个等级,前四个等级由css选择器决定,后两个等级由书写形式合特定语法决定。
每个等级都有自己的分数,优先级就是各个等级的选择器加起来分数大的高。如果分数一样,则后写的优先级高。

0级

通配选择器、选择符和逻辑组合伪类。

通配选择器:*;

选择符:+、>、~、空格、||

逻辑组合伪类::not() :is() :where 等 (这些伪类本身并不影响css优先级,影响优先级的是括号里面的选择器)

分数:0

一级

标签选择器和伪元素选择器

分数:1

div {
  color: red;
}
::selection {
  color: red;
}

二级

类选择器,属性选择器,伪类

分数:10

.my-class {
  color: red;
}
:hover {
  color: red;
}
[href='#'] {
  color: red;
}

三级

ID选择器

分数:100

#myID {
  color: red;
}

四级

style属性内联

分数:1000

<div style="color: red"></div>

五级

! important

分数:10000

.my-class {
  color: red !important; /* 10,000 points */
  background: white; /* 10 points */
}

注意:尽量不要使用id选择器,原因:优先级太高;会和js耦合,容易产生bug。也尽量不要使用内联样式和important,优先级太高,后面改的时候不好改。

一些例子:

/*11 :not()虽然为0,但是里面的class要算分*/
div:not(.my-class) {
  color: red;
}

<a class="my-class another-class" href="#">A link</a>

<style>
/*1*/
a {
  color: red;
}

/*11*/
a.my-class {
  color: green;
}

/*21*/  
a.my-class.another-class {
  color: rebeccapurple;
}

/*31*/
a.my-class.another-class[href] {
  color: goldenrod;
}

/*41*/
a.my-class.another-class[href]:hover {
  color: lightgrey;
}
</style>

一般的选择器简易记法

image
a.my-class.another-class[href]:hover {
  color: lightgrey;
}
/*0个id选择器,4个二级选择器[类/属性/伪类],1个一级选择器[标签/伪元素]*/
/*所以分数为041 —— 41*/
上一篇 下一篇

猜你喜欢

热点阅读