:target 選中 URL 片段識別符(#id)對應的元素。結合語意化 HTML 錨點,可實作多種互動模式,且天然支援瀏覽器前進後退、書籤分享、深層連結。
<!-- HTML -->
<div class="tabs" role="tablist">
<a href="#panel1" role="tab" aria-selected="true">面板一</a>
<a href="#panel2" role="tab">面板二</a>
<a href="#panel3" role="tab">面板三</a>
</div>
<div class="tab-panels">
<section id="panel1" role="tabpanel" aria-labelledby="tab1">內容一</section>
<section id="panel2" role="tabpanel" aria-labelledby="tab2">內容二</section>
<section id="panel3" role="tabpanel" aria-labelledby="tab3">內容三</section>
</div>
<!-- CSS -->
.tab-panels section { display: none; }
.tab-panels section:target { display: block; }
/* 無 hash 時顯示第一個 */
.tab-panels section:first-child { display: block; }
.tab-panels section:target ~ section:first-child { display: none; }
/* 標籤視覺狀態 (需 :has() 或 JS 輔助完整 ARIA) */
.tabs a { /* 基礎樣式 */ }
.tabs a[href="#panel1"]:target { /* 活躍樣式 */ }
<a href="#lightbox1">開啟燈箱</a>
<div id="lightbox1" class="lightbox">
<div class="lightbox-content">
<img src="large.jpg" alt="">
<a href="#" class="close">×</a>
</div>
</div>
.lightbox { display: none; position: fixed; inset: 0; background: rgba(0,0,0,.8); }
.lightbox:target { display: flex; align-items: center; justify-content: center; }
.lightbox .close { position: absolute; top: 1rem; right: 1rem; }
<a href="#sidebar" class="toggle">☰</a>
<aside id="sidebar">...</aside>
#sidebar { transform: translateX(-100%); transition: transform .3s; }
#sidebar:target { transform: translateX(0); }
#sidebar:target ~ .toggle { /* 變更圖示 */ }
history.replaceState() (需 JS) 緩解。aria-selected、aria-hidden 需 JS 同步,純 CSS 無法動態修改屬性。:target 適合靜態內容導向的輕量互動(文檔錨點高亮、簡易分頁、燈箱),複雜應用仍建議使用 JavaScript 狀態管理。