Appearance
CSS 选择器及其优先级?
1.选择器种类
选择器类型 | 示例 | 描述 |
---|---|---|
通配符选择器 | * | 匹配所有元素。 |
元素选择器/标签选择器 | element | 根据元素的标签名进行匹配。 |
类选择器 | .class | 根据元素的类名进行匹配。 |
ID 选择器 | #id | 根据元素的唯一 ID 属性进行匹配。 |
属性选择器 | [attribute] | 根据元素的属性名进行匹配。 |
伪元素选择器 | ::before , ::after | 选择元素的伪元素,用于在元素内容前后插入内容。 |
伪类选择器 | :hover , :nth-child() | 根据元素的状态或位置进行匹配,例如鼠标悬停状态或元素在父元素中的位置。 |
后代选择器 | ancestor descendant | 选择嵌套在另一个元素内部的元素。 |
子代选择器 | parent > child | 选择作为另一个元素的直接子元素的元素。 |
相邻兄弟选择器 | prev + next , prev ~ next | 选择相邻兄弟元素中的特定元素,可以选择直接相邻的兄弟元素或任意位置的兄弟元素。 |
2.选择器优先级
选择器类型 | 特殊性值 | 示例 |
---|---|---|
通配符选择器 | (0, 0, 0) | * |
元素选择器 | (0, 0, 1) | div , p , a |
伪元素选择器 | (0, 0, 1) | ::before , ::after |
类选择器 | (0, 1, 0) | .myClass |
伪类选择器 | (0, 1, 0) | :hover , :nth-child(2n) |
属性选择器 | (0, 1, 0) | [data-attribute="value"] |
ID 选择器 | (1, 0, 0) | #myId |
内联样式(style 属性) | 最高优先级 | <div style="color: red;"> |
!important | color: blue !important; |
- :is()、:not()或:has() 除了外面的选择器,如果()里面也有选择器,那么按照基础选择器优先级最大的计算
- :nth-child()或:nth-last-child() 计算里面选择器的同时加 1.
- :where() 完全不计算里面的优先级,只计算: 前面的选择器优先级
选择器 | 权重 (0, 0, 0) |
---|---|
* | 0, 0, 0 |
li | 0, 0, 1 |
ul li | 0, 0, 2 |
ul ol+li | 0, 0, 3 |
h1 + *[rel=up] | 0, 1, 1 |
ul ol li.red | 0, 1, 3 |
li.red.level | 0, 2, 1 |
#app | 1, 0, 0 |
#app:not(div) | 1, 0, 1 |
.foo :is(.bar, #baz) | 1, 1, 0 |
[id="app"] | 0, 1, 0 |
3.请给出【Sausage】的字体颜色值?
html
<style>
body {
color: grey;
}
/* (2,2,0) */
#shop .favorite:not(#shop).highlight {
color: red;
}
/* (1,3,0) */
#shop .highlight:nth-of-type(1):nth-last-of-type(1) {
color: blue;
}
</style>
<ul class="shopping-list" id="shop">
<li><span>Milk</span></li>
<li class="favorite" id="must-buy">
<span class="highlight">Sausage</span>
</li>
</ul>
<style>
body {
color: grey;
}
/* (2,2,0) */
#shop .favorite:not(#shop).highlight {
color: red;
}
/* (1,3,0) */
#shop .highlight:nth-of-type(1):nth-last-of-type(1) {
color: blue;
}
</style>
<ul class="shopping-list" id="shop">
<li><span>Milk</span></li>
<li class="favorite" id="must-buy">
<span class="highlight">Sausage</span>
</li>
</ul>