邻接的 CSS 选择器

时间:2022-10-19
本文介绍了邻接的 CSS 选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

似乎 CSS 是右关联的,并且与编程语言不同,您不能用括号来影响它.

我有这个一般结构:

<div class='pizza'></div></div><p>选择我!选择我!</p>

<div class="披萨"><p>不要选择我!</p></div></div>

我无法找出一个 <p> 的选择器,该选择器跟随一个包含 <div class=" 的兄弟 <div>比萨">.

我试过这个,但 CSS 的从右到左的关联性并没有产生我想要的:

div >div.pizza + p

我知道这是不对的.

有人可以指点一下吗?

解决方案

组合器,至少是目前可用的组合器,只能表达两个元素之间的关系.正如您正确观察到的那样,您无法更改组合子的关联性.正因为如此,而且没有父元素对应于子元素的 > 组合子,所以不可能构造一个 CSS 选择器来表示 both

div >div.pizza

div + p

每个选择器中的第一个 div 代表相同的元素.

这个关联性问题可以使用建议的 :has() 伪类来解决,它在功能性伪类中为您提供了相对选择器语法,允许您将这样的选择器构造为

div:has(> div.pizza) + p

其中 p 是最外层选择器的主题.相对选择器 >div.pizza 是 范围 到第一个 div 选择器——本质上,这是上面前两个复杂选择器的组合,:has() 伪类的作用与任何其他简单选择器一样.

目前尚不清楚这个提议的功能是否会在 CSS 中实现.

查看我对这些相关问题的回答以了解更多信息:

  • CSS 选择器中是否允许使用括号?
  • 如何使用CSS根据页面中另一个元素的状态选择一个元素?

It seems CSS is right associative, and unlike programming languages, you cannot influence this with parentheses.

I have this general structure:

<div>
   <div class='pizza'></div>
</div>
<p>Select me!  Select me!</p>

<div>
   <div class="pizza">
      <p>Do NOT select me!</p>
   </div>
</div>

I can't figure out the selector for a <p> that follows a sibling <div> containing a <div class="pizza">.

I tried this but the right-to-left associativity of CSS does not yield what I want:

div > div.pizza + p

I know this isn't right.

Can someone offer a pointer?

解决方案

Combinators, at least the ones that are currently available, can only express a relationship between exactly two elements. As you've correctly observed, you cannot change the associativity of combinators. Because of this, and the fact that there is no parent counterpart to the > combinator for child elements, it is not possible to construct a CSS selector that represents both

div > div.pizza

and

div + p

where the first div in each selector represents the same element.

This associativity issue can be solved using the proposed :has() pseudo-class, which provides you with a relative selector syntax within a functional pseudo-class, allowing you to construct such selectors as

div:has(> div.pizza) + p

where p is the subject of the outermost selector. The relative selector > div.pizza is scoped to the first div selector — essentially, this is a combination of both of the first two complex selectors above, with the :has() pseudo-class acting just like any other simple selector.

It is not known yet if this proposed feature will be implemented in CSS.

See my answers to these related questions for more info:

  • Are parentheses allowed in CSS selectors?
  • How do I select an element based on the state of another element in the page with CSS?

这篇关于邻接的 CSS 选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一条:带有嵌套元素的 CSS nth-of-type 选择器 下一条:CSS nth-child 应用奇偶规则,但每 4 项切换一次

相关文章

最新文章