問題描述
我需要一個 css3 選擇器來定位一個元素,當 :target 等于元素的 id(簡單)或當 :target
為空(不可能?).很難解釋,我舉個簡單的例子.
I need a css3 selector to target an element when the :target equals the id of the element (easy) or when the :target
is empty (impossible?). It’s hard to explain, so let me give you a simple example.
div {
background: blue;
}
div:target, div:no-target {
background: red;
}
當然 :no-target
偽類不存在 ;).不使用 Javascript 有沒有辦法解決這個問題?提前致謝!
But of course the :no-target
pseudo class doesn’t exist ;). Is there a way around this without using Javascript? Thanks in advance!
推薦答案
嘆息.我覺得我正在復活一個死去的話題,但它需要一個真正的答案.
Sigh. I feel like I'm resurrecting a dead topic, but it needs a real answer.
僅使用 CSS 就可以做到這一點,只需使用 :last-child
和 一般兄弟組合子,形式為 :target ~ :last-child
:
It's possible to do this with CSS alone, just by using :last-child
and a general sibling combinator, in the form of :target ~ :last-child
:
.pages > .page:target ~ .page:last-child,
.pages > .page {
display: none;
}
/* :last-child works, but .page:last-child will not */
.pages > :last-child,
.pages > .page:target {
display: block;
}
這些規則適用于以下步驟:
The rules applies in the following steps:
- 隱藏所有頁面
- 同時顯示目標頁面和最后一頁
- 如果一個頁面被定位,隱藏最后一頁(
.page:target ~ .page:last-child
)
(現場示例)
顯然,這與 舊版本中接受的答案非常相似,前面提到的相關帖子.
這篇關于:target 為空時的 CSS 選擇器的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!