:target-within

實驗性: 這是一種 實驗性技術
在生產環境中使用之前,請仔細檢視 瀏覽器相容性表

:target-within CSS 偽類 代表一個元素,該元素是一個目標元素或 *包含* 一個目標元素。目標元素是一個具有與 URL 片段匹配的 id 的唯一元素。換句話說,它代表一個自身被 :target 偽類匹配或其後代被 :target 匹配的元素。(這包括 陰影樹 中的後代。)

css
/* Selects a <div> when one of its descendants is a target */
div:target-within {
  background: cyan;
}

語法

css
:target-within {
  /* ... */
}

示例

突出顯示文章

如果文章內部的任何內容被直接連結,則可以使用 :target-within 偽類來突出顯示該文章。:target 偽類也被用來顯示哪個專案被選中。

HTML

html
<h3>Table of Contents</h3>
<ol>
  <li><a href="#p1">Jump to the first paragraph!</a></li>
  <li><a href="#p2">Jump to the second paragraph!</a></li>
</ol>

<article>
  <h3>My Fun Article</h3>
  <p id="p1">
    You can target <i>this paragraph</i> using a URL fragment. Click on the link
    above to try out!
  </p>
  <p id="p2">
    This is <i>another paragraph</i>, also accessible from the links above.
    Isn't that delightful?
  </p>
</article>

CSS

css
article:target-within {
  background-color: gold;
}

/* Add a pseudo-element inside the target element */
p:target::before {
  font: 70% sans-serif;
  content: "►";
  color: limegreen;
  margin-right: 0.25em;
}

/* Style italic elements within the target element */
p:target i {
  color: red;
}

結果

規範

規範
選擇器級別 4
# the-target-within-pseudo

瀏覽器相容性

BCD 表只在瀏覽器中載入

另請參閱