CSS 选择器
# 优先级
:root 选择器特定性:0-1-0
html 选择器特定性:0-1-1
*星號選擇器的級別是 0–0–0
标签选择器/伪元素 < 类选择器/属性选择器/伪类 < ID 选择器
# :has()
选择器允许我们根据元素的后代或任何后续元素来确定其样式
/** 类名为 ‘post’ 下是否含有 a 或 span 标签,有则设置 ‘post’ 类所在标签的颜色为红色 */ .post:has(a, span) { color: red; } <div class="post"> 666 <a href="http://">text</a> </div>
/** 类名为 ‘post’ 是否含有 p 标签兄弟标签,有则设置 ‘post’ 类所在标签的颜色为红色 */ .post:has(+ p) { color: red; } <div class="post">text1</div> <p>text2</p>
# :not()
- 标签中不含有类,则设置下划线样式
:not([class]) {
text-decoration-thickness: 2px; /** 下划线相对厚度 */
text-underline-offset: 0.15em; /** 下划线偏移量 */
}
<a href="http://">text1</a>
<a class="text" href="http://">text2</a>
# :is()
以选择器列表作为参数,不能选择伪元素,伪元素在:is()的选择器列表中无效
/** 标签中含有类名为 ‘text’,则设置颜色为红色 */ :is([class="text"]) { color: red; } <a class="text" href="http://">text</a>
# :where()
父标签为 p 的 span 标签鼠标悬浮为红色
:where(p) span:hover { color: red; cursor: pointer; } <p> <span>text1</span> <i>text2</i> </p>
# :is()
与 :where()
异同
在 CSS 中,当使用选择器列表时,如果任何一个选择器无效,则整个列表将被视为无效。使用
:is()
或:where()
时,如果一个选择器无法解析,整个选择器列表不会被视为无效,而是会忽略不正确或不支持的选择器,并使用其他的选择器。/** 即使在不支持 :unsupported 的浏览器中,仍将正确解析 :valid */ :is(:valid, :unsupported) { /* … */ } /** 在不支持 :unsupported 浏览器中即使它们支持 :valid,仍将忽略 */ :valid, :unsupported { /* … */ }
# :focus-within
当元素或其任意后代元素被聚焦时,将匹配该元素
label:focus-within { font-weight: bold; } <label>name: <input name= 'Name' type= 'text' / ></label>;
# :placeholder
占位样式
input:placeholder { font-weight: bold; } <label>name: <input name= 'Name' type= 'text' / ></label>;
# :empty
选择没有子元素(包括文本节点)的元素。
div{ width: 100px; height: 100px; background-color: #0f0; } div:empty{ background-color: #f00; } <div></div> <div>666</div> <div> <span></span> </div>