用 target 選擇器改變其他 HTML 元素的樣式
target 是一個虛擬類別選擇器,用途在於讓我們設定目標對象的樣式。
CSS 的寫法如下:
.類別選擇器:target{
.....
}
target 基礎應用
在這個範例中,我們藉由 <a href="#top">
來動態地操控 id
是 top
的 HTML 元素樣式。
<a href="#top">上面變色</a>
<a href="#">不變色</a>
<a href="#bottom">下面變色</a>
<div class="change" id="top">上面變色</div>
<div class="change" id="bottom">下面變色</div>
<a href="#top">
對應的 target
就是 id 為 top
的 HTML 元素。
.change:target{
background: orange;
width:200px;
}
當我們點選其他連結的時候,連結對應 id
的元素也會改變樣式,同時其他元素的樣式會恢復原狀。
target 進階應用:燈箱效果
利用 <a href="#example1">
來打開燈箱。
然後用 <a href="#" class="close">
來關掉燈箱效果。
<ul>
<li><a href="#example1">打開燈箱 #1</a></li>
<li><a href="#example2">打開燈箱 #2</a></li>
</ul>
<div class="lightbox" id="example1">
<figure>
<!-- 關閉燈箱效果 -->
<a href="#" class="close"></a>
<figcaption>我是燈箱一</figcaption>
</figure>
</div>
<div class="lightbox" id="example2">
<figure>
<!-- 關閉燈箱效果 -->
<a href="#" class="close"></a>
<figcaption>我是燈箱二</figcaption>
</figure>
</div>
/* 先把燈箱設為 不顯示 */
.lightbox {
display: none;
}
/* 利用 target 來打開燈箱 */
.lightbox:target {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
}
/* Lightbox content */
.lightbox figcaption {
width: 25rem;
position: relative;
padding: 1.5em;
background-color: lightblue;
}
/* Close button */
.lightbox .close {
position: relative;
display: block;
}
.lightbox .close::after {
right: -1rem;
top: -1rem;
width: 2rem;
height: 2rem;
position: absolute;
display: flex;
z-index: 1;
align-items: center;
justify-content: center;
background-color: black;
border-radius: 50%;
color: white;
content: "×";
cursor: pointer;
}
/* Lightbox overlay */
.lightbox .close::before {
left: 0;
top: 0;
width: 100%;
height: 100%;
position: fixed;
background-color: rgba(0,0,0,.7);
content: "";
cursor: default;
}
用 target 選擇器改變其他 HTML 元素的樣式
https://popeye-ux.github.io/2023/01/19/cssTarget-1/