[英]CSS Select Sibling of An Element with A Specific Sub-Element?
下面的代碼片段是包含許多 .step 元素的更大結構的一部分。
我需要匹配所有.stepText
旁邊,是元素.stepTitleAndImages ul.standard
換句話說,匹配所有.stepText
具有的元素.step
有父.stepTitleAndImages
孩子有.stepImages.standard
孩子
<div class="step">
<div class="stepTitleAndImages">
<h3 class="stepTitle"></h3>
<ul class="stepImages standard"></ul>
<div class="clearer"></div>
</div>
<div class="stepText "></div> **HOW TO SELECT ALL ELEMENTS LIKE THIS ONE?**
<div class="clearer"></div>
</div>
<div class="step">
<div class="stepTitleAndImages">
<h3 class="stepTitle"></h3>
<ul class="stepImages medium"></ul>
<div class="clearer"></div>
</div>
<div class="stepText "></div>
<div class="clearer"></div>
</div>
PS:我無法修改 HTML。 不能使用純 CSS 以外的任何東西。
只需使用它來選擇第一種情況
.step:nth-child(1) .stepText {
... Your CSS here
}
第二次使用
.step:nth-child(2) .stepText {
... Your CSS here
}
選擇兩者使用
.step .stepText {
... Your CSS here
}
那么你應該為此需要jquery
僅使用純 CSS 還不能選擇父級兄弟姐妹,您可以通過一行 jquery 來實現:
$('ul.standard').parent().siblings(".stepText").css(...your CSS here);
這不能用你的 HTML 結構和純 CSS 來完成。 最接近您的問題的解決方案是更改 HTML 結構並使用純 CSS,將standard
類移動到其父標簽:
<div class="stepTitleAndImages standard"> <h3 class="stepTitle"></h3> <ul class="stepImages"></ul> <div class="clearer"></div> </div>
這將允許您使用相鄰的兄弟選擇器( +
),如果第二個選擇器是第一個的直接下一個選擇器,則它匹配第二個選擇器,如下所示:
.stepTitleAndImages.standard + .stepText { /* Styles */ }
一種更靈活的方法是使用通用兄弟選擇器,它可以匹配第一個選擇器之前的任何兄弟,而不僅僅是直接的下一個:
.stepTitleAndImages.standard ~ .stepText { /* Styles */ }
:has
偽類正在由 Mozilla 開發,但它還沒有在任何穩定的瀏覽器上運行。 有了它,以及你的 HTML 結構,你可以去:
.stepTitleAndImages:has(.standard) + .stepText { /* Styles */ }
不幸的是,目前您無法僅使用 CSS(以及您的 HTML 結構)以任何其他方式解決此問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.