有这样的事情,如“全包的兄弟姐妹” CSS选择器? [英] Is there such a thing as an "all inclusive sibling" CSS selector?

查看:163
本文介绍了有这样的事情,如“全包的兄弟姐妹” 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.

其他选择器:

+ selector(aka adjacent sibling selector )只会选择纸杯蛋糕:

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 */
}

selector(aka general sibling selector )只会选择纸杯蛋糕和猪仔:

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 */
}

匹配您的 p 元素,即使 none 他们有类。目前不可能仅在给定元素的存在的情况下选择元素的兄弟元素(这是兄弟组合器的目的 - 建立两个兄弟之间的关系元素)。

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天全站免登陆