問題描述
通常,我擅長 CSS,但我似乎無法弄清楚這一點.如果我的結構是
<h2 class="open">1</h2><h2>2</h2><h2>3</h2><h2>4</h2><h2>5</h2></div>如何使用帶有 CSS 的 .open
類來定位所有同級 h2?我的主要問題是兄弟選擇器(.open + h2
)只會針對緊隨 .open
之后的 h2.
解決方案 你可以使用 ~
代替 +
選擇以下所有兄弟:
.open ~ h2
如果您需要選擇所有不是 .open
的 h2
元素,無論它們在 .open
之前還是之后,都沒有同級組合器.你需要使用 :not()
代替:
h2:not(.open)
如果您需要將選擇限制為 div
父母,則可以選擇使用子組合器:
div >h2:not(.open)
Usually, I'm good with CSS, but I can't seem to figure this one out. If I have a structure of
<div>
<h2 class="open">1</h2>
<h2>2</h2>
<h2>3</h2>
<h2>4</h2>
<h2>5</h2>
</div>
how can I target all of the sibling h2s using the .open
class with CSS? My main issue is that sibling selectors (.open + h2
) will only target the h2 immediately following .open
.
解決方案 You can select all the following siblings using ~
instead of +
:
.open ~ h2
If you need to select all h2
elements that aren't .open
whether they precede or follow .open
, there is no sibling combinator for that. You'll need to use :not()
instead:
h2:not(.open)
Optionally with a child combinator if you need to limit the selection to div
parents:
div > h2:not(.open)
這篇關于CSS 兄弟選擇器(選擇所有兄弟)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!