| 選擇器 | 名稱 | 匹配關係 | 範例 |
|---|---|---|---|
E + F | 相鄰兄弟選擇器 | F 緊接在 E 後方,同父級 | input:checked + label |
E ~ F | 通用兄弟選擇器 | F 在 E 後方任意位置,同父級 | input:checked ~ .panel |
E > F | 子代選擇器 | F 是 E 的**直接**子元素 | .menu > li |
E F | 後代選擇器 | F 是 E 的任意層級後代 | .article p |
利用 :checked + 相鄰兄弟選擇器,隱藏原生控件,自定義樣式。
<fieldset>
<legend>選擇顏色</legend>
<label><input type="radio" name="color" value="red"><span class="label-text">紅色</span></label>
<label><input type="radio" name="color" value="blue"><span class="label-text">藍色</span></label>
</fieldset>
/* 隱藏原生 input */
input[type="radio"] { position: absolute; opacity: 0; pointer-events: none; }
/* 自定義圓點 */
.label-text::before {
content: '';
display: inline-block;
width: 1em; height: 1em;
border: 2px solid #ccc;
border-radius: 50%;
margin-right: .5em;
vertical-align: -0.2em;
transition: border-color .2s, background .2s;
}
/* 選中態:input:checked + 緊鄰的 span */
input:checked + .label-text::before {
border-color: #3498db;
background: #3498db;
/* 內部白點 */
box-shadow: inset 0 0 0 3px #fff;
}
關鍵點:input 與 span 必須**同層級且相鄰**,+ 才生效。若中間隔著其他標籤,改用 ~。
<div class="accordion">
<input type="checkbox" id="item1" hidden>
<label for="item1">標題 1</label>
<div class="panel">內容 1...</div>
<input type="checkbox" id="item2" hidden>
<label for="item2">標題 2</label>
<div class="panel">內容 2...</div>
</div>
.accordion .panel {
max-height: 0;
overflow: hidden;
transition: max-height .3s ease;
}
/* 通用兄弟選擇器:label 後方的 .panel */
.accordion input:checked ~ .panel {
max-height: 500px; /* 足夠大的值 */
}
優點:無 JS、鍵盤可訪問 (Tab 切換、Space 觸發)、語義化。
缺點:max-height 動畫需估算最大高度;無法動畫 height: auto。
<div class="comment-thread">
<article class="comment">
<header>用戶 A</header>
<p>內容...</p>
<div class="replies">
<article class="comment">...</article> /* 孫子輩 */
</div>
</article>
</div>
/* 僅選直接子評論,不含回覆 */
.comment-thread > .comment { border-left: 3px solid #3498db; padding-left: 1rem; }
/* 選所有層級評論 */
.comment-thread .comment { color: #333; }
> 確保樣式不滲透到任意深度巢狀,避免副作用。
<div class="field">
<input type="email" required>
<span class="error-msg">郵箱格式不正確</span>
</div>
.field { position: relative; }
.error-msg {
position: absolute;
left: 0; bottom: -1.5em;
color: red; font-size: .875rem;
opacity: 0; visibility: hidden;
transition: opacity .2s, visibility .2s;
}
/* input 緊鄰的錯誤訊息 */
.field input:invalid:not(:placeholder-shown) + .error-msg {
opacity: 1; visibility: visible;
}
/* 列表項目 ≥ 5 時,改為多欄佈局 */
.list-item:nth-last-child(n+5),
.list-item:nth-last-child(n+5) ~ .list-item {
width: 50%; float: left; /* 或 flex/grid */
}
+ / ~ 不生效> 選到孫子輩+ (相鄰) / ~ (通用兄弟) / > (子代) 是 CSS 結構選擇的精準手術刀。善用它們配合 :checked/:focus/:valid 等狀態偽類,能實現**零 JavaScript 的交互邏輯**,減少包體積、提升效能、增強韌性。掌握選擇器組合,是 CSS 進階的分水嶺。