has选择器基本用法

1. 选择包含特定子元素的元素,即 选择父元素

li:has(p, #h3)  li:has(p.cls)  a:has(> img)  .item:has(.thumb:hover)

1.1 检查是否有空元素

.box:has(span:empty)

1.2 检查是否有多个孩子节点

.box:has(p, span, h3, .item)

2. 选择紧邻或包含特定后置兄弟元素的元素

label:has(+ input:invalid)::before   h1:has(+ p)   label:has(+input:required)

2.1 has配合兄弟选择器,实际上是实现了前置兄弟选择器

+ 和 ~ 都是后置选择器,只能选择后置兄弟

has(~.sel)  含义是后置兄弟有.sel的元素,也就是 .sel 之前的兄弟元素

.box:has(+ .select-my-previous-sibling)

2.2 ~和has同时实现,实现范围选择器

.select~span:has(~.select)  //选择.select之后,下一个.select之前的元素

3. has可配合not选择器使用,实现反选

检查不包含特定元素,或者 检查后方无特定元素

li:not(:has(p, span))   //不包含p或span的li
.date:not(:has(.select~.select))  //不包含两个.select的.date元素
.date:not(:has(.select+.select))  //不包含两个紧邻.select的.date元素

4. has可使用数量和位置选择器

p:has(>br:first-child)  //选择首子元素为br的p
p:has(>br:only-child)   //选择仅有子元素br的p

5. has可判断元素个数

/*只有0个元素*/
.con:not(:has(*)){   
    background: yellow;
}
/*只有1个元素*/
.con:has(> :last-child:nth-child(1)){   
    background: yellow;
}
/*只有2个元素*/
.con:has(> :last-child:nth-child(2)){   
    background: yellow;
}
/*只有3个元素*/
.con:has(> :last-child:nth-child(3)){   
    background: yellow;
}

 

 

参考: CSS :has 判断子元素个数 

posted @ 2023-08-14 10:20  全玉  阅读(136)  评论(0编辑  收藏  举报