問題描述
似乎 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 選擇器的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!