Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> CSS

CSS General Sibling Selector (~): Bộ chọn anh em chung

Bộ chọn anh em chung (general sibling selector) trong CSS được dùng để chọn tất cả các phần tử theo sau phần tử đầu tiên sao cho cả hai là con của cùng một parent.

Cú pháp

element ~ element {
    /* declarations */
}

Khác với adjacent sibling (+) chỉ chọn phần tử liền kề ngay sau, ~ chọn tất cả phần tử sau đó (cùng parent).

Ví dụ 1: ul sau p

<!DOCTYPE html>
<html>
<head>
<style>
* { float: left; padding-left: 14px; list-style: none; }
p ~ ul {
    box-shadow: inset 4px 0 3px lime;
}
</style>
</head>
<body>
<ul><li><img src="pl-sql.png"></li></ul>
<p>We provide learning tutorials, quizzes and video tutorials.</p>
<ul><li>Tutorials on databases and programming languages.</li></ul>
<ul><li>Quizzes to check knowledge...</li></ul>
<ul><li>Video Tutorials...</li></ul>
<ul>
    <li><img src="mongodb.png"></li>
    <li><img src="db2.png"></li>
    <li><img src="sql.png"></li>
</ul>
</body>
</html>

Kết quả: UL đầu tiên (trước p) không bị style. 4 UL sau p đều có box-shadow lime.

Ví dụ 2: p sau img

<!DOCTYPE html>
<html>
<head>
<style>
* { float: left; padding: 10px; list-style: none; }
img ~ p {
    background-color: burlywood;
}
</style>
</head>
<body>
<p>This is demo text.</p>
<img src="big-data-analytics-mini-logo.jpg">
<p>Learn Big Data Analytics at no cost.</p>
</body>
</html>

Kết quả: P đầu tiên (trước img) không bị style. P thứ hai (sau img) có nền burlywood.

So sánh: + vs ~

SelectorTênChọnVí dụ khớp
h2 + pAdjacent sibling1 phần tử p ngay sau h2P đầu tiên sau h2
h2 ~ pGeneral siblingTất cả p sau h2P thứ 1, 2, 3... sau h2

Ứng dụng thực tế

/ * Divider giữa các section */
h2 ~ h2::before {
    content: "";
    display: block;
    height: 2px;
    background: linear-gradient(90deg, transparent, #ccc, transparent);
    margin: 2rem 0;
}

/ * Style cho content sau figure */
figure ~ p { margin-top: 1.5rem; font-style: italic; }

/ * Form: label cho input sau khi có error */
.error ~ .help-text { color: red; display: block; }

/ * Accordion: mở panel sau khi click */
.accordion-toggle:checked ~ .accordion-panel { display: block; }

Lưu ý

  • Cả hai phần tử phải có cùng parent (siblings)
  • Selector đầu tiên không bị style — chỉ các phần tử sau nó
  • Không quan tâm khoảng cách (có thể có phần tử khác giữa)
  • Không chọn được phần tử trước (chưa có "previous sibling selector" trong CSS, dùng :has() mới)