是否有“包罗万象的兄弟姐妹"之类的东西?CSS 选择器? [英] Is there such a thing as an "all inclusive sibling" CSS selector?

查看:22
本文介绍了是否有“包罗万象的兄弟姐妹"之类的东西?CSS 选择器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 HTML:

<p>Doggies</p>
<p class="green_guys">Froggies</p>
<p>Cupcakes</p>
<p>Piggies</p>

当用于选择 green_guys 的兄弟姐妹时,一个全包的兄弟姐妹选择器(如我所愿)将选择小狗纸杯蛋糕和小猪.

An all inclusive sibling selector (as I wish it to be), when used to select green_guys' siblings, would select the doggies cupcakes and piggies.

其他选择器:

+ 选择器(又名相邻兄弟选择器)只会选择纸杯蛋糕:

The + selector (a.k.a. adjacent sibling selector) would only select the cupcakes:

.green_guys + p {
    /* selects the <p> element that immediately follows .green_guys */
}

~ 选择器(又名通用兄弟选择器)只会选择纸杯蛋糕和小猪:

The ~ selector (a.k.a. general sibling selector) would only select the cupcakes, and piggies:

.green_guys ~ p {
    /* selects all <p> elements that follow .green_guys */
}

推荐答案

没有向后或向后看的兄弟组合子,只有向前看的相邻和一般兄弟组合子.

There is no sibling combinator that looks backward or around, only the adjacent and general sibling combinators that look forward.

您可以做的最好的事情是确定一种方法,将选择限制为仅具有相同父级的这些 p 元素,然后选择 p 子级 :not(.green_guys).例如,如果父元素的 ID 为 #parent,则可以使用此选择器:

The best you can do is determine a way to limit selection only to these p elements with the same parent, and then select the p children that are :not(.green_guys). If the parent element has an ID of #parent, for example, you can use this selector:

#parent > p:not(.green_guys) {
    /* selects all <p> children of #parent that are not .green_guys */
}

但是,即使 none 元素具有类,上述内容仍将匹配您的 p 元素.目前不可能仅在给定元素 存在 的情况下选择该元素的兄弟姐妹(这是兄弟组合器的目的 - 建立 两个 兄弟之间的关系元素).

However the above will still match your p elements even if none of them have the class. It is currently not possible to select the siblings of an element only given the existence of said element (which is the purpose of a sibling combinator — to establish a relationship between two sibling elements).

选择器 4 的 :has()有望在不需要前置兄弟组合器的情况下纠正此问题,从而产生以下解决方案:

Selectors 4's :has() will hopefully rectify this without the need for a preceding-sibling combinator, resulting in the following solution:

p:has(~ .green_guys), .green_guys ~ p {
    /* selects all <p> elements that are siblings of .green_guys */
}

如果父元素的所有子元素都没有该类,这将不匹配任何内容.

This will not match anything if none of the children of the parent element have the class.

这篇关于是否有“包罗万象的兄弟姐妹"之类的东西?CSS 选择器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆