【问题标题】:Is it possible to target "no target" in CSS?是否可以在 CSS 中定位“无目标”?
【发布时间】:2026-01-27 12:30:02
【问题描述】:

是否有“没有片段标识符存在”的 css 选择器?与:target相反。

问题是,我正在制作一个文档,其中的不同部分是可见的,具体取决于您提供的片段标识符。将其视为一个 sprite 文件,仅适用于 HTML。

原来是这样的

<style>
 section {display:none}
 section:target {display:block}
</style>

<body>
 <section id="one">The first block (showing with #one)</section>
 <section id="two">The second block (showing with #two)</section>
 <section id="three">The third block (showing with #three)</section>
</body>

如果第一部分在地址栏上显示为document.html#one 等,则用户会看到它。

这个想法是浏览器将缓存html页面(因为它只是静态html)并且在显示另一块文本时不需要加载其他内容,从而最大限度地减少服务器负载。

但是当您在没有片段标识符的情况下调用该文件时,该文件看起来非常空,所以我想知道在这种情况下是否有一种方法可以使所有文件都可见,而没有任何隐藏部分。只有 CSS,没有 JS 或服务器端处理;否则它不会是静态 HTML!

编辑:
与建议的重复项不同,我想在没有片段标识符时“简单地”显示整个文档,而不仅仅是一个特定的元素。
换句话说,默认(在没有任何#的情况下)应该是显示所有内容;仅当存在 # 时,才应隐藏除目标之外的所有内容。
副本根本没有解决这种情况。

【问题讨论】:

  • 如何最小化服务器负载? HTML 文件已提供并完全下载,即使您隐藏该部分,它们仍会被加载和下载。所以我不太明白你认为你是如何最小化的。
  • @BramVanroy 在这个特定的用例中,我在整个网站上多次链接到文件,使用不同的片段标识符。所以它只会被下载一次(至少我希望如此)并且在第一次之后它将来自用户的缓存。
  • my comment on one of the proposed duplicates。由于 :target 伪匹配目标元素,那么当 没有目标元素时,您期望“:target 的反面”匹配什么?
  • @BoltClock 我期望不高,但我希望有一些非常聪明的东西,我没想过要尝试的东西。类似的东西在那边↓事实上。

标签: html css css-selectors fragment-identifier


【解决方案1】:

使用一些额外的标记和更详细和更具体的 CSS 来编写,以避免使用 javaScript。 每次更新 HTML 结构时都需要更新 .

:target ~section {
  display:none;
}
#one:target ~.one,
#two:target ~.two,
#three:target ~.three  {
  display:block;
}
<nav>
  <a href="#one">One</a> 
  <a href="#two">Two</a>
  <a href="#three">Three</a>
  <a href="#">None of below targets</a>
</nav>
<!-- html anchor to allow use of :target ~ selectors -->
<a id="one"></a>
<a id="two"></a>
<a id="three"></a>
<!-- end anchor -->
<section class="one">The first block (showing with #one)</section>
<section class="two">The second block (showing with #two)</section>
<section class="three">The third block (showing with #three)</section>

【讨论】: