CSS General Sibling Selector (~) ใช้เลือกองค์ประกอบ ทั้งหมด ที่อยู่หลังองค์ประกอบแรก โดยที่ทั้งคู่เป็นลูกของพาเรนต์เดียวกัน (ต่างจาก Adjacent Sibling + ที่เลือกแค่ตัวถัดไปทันที)
ไวยากรณ์ (Syntax)
element ~ element {
/* declarations */
}
ตัวอย่างที่ 1: p ~ ul (ul ทุกตัวหลัง 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="https://www.tutorialspoint.com/images/pl-sql.png"></li></ul>
<p>We provide learning tutorials, quizzes and video tutorials.</p>
<ul>
<li>Tutorials on databases and programming languages.</li>
<li>Quizzes to check knowledge of databases and languages.</li>
<li>Video Tutorials to easily understand the technologies.</li>
</ul>
<ul>
<li><img src="https://www.tutorialspoint.com/images/mongodb.png"></li>
<li><img src="https://www.tutorialspoint.com/images/db2.png"></li>
<li><img src="https://www.tutorialspoint.com/images/sql.png"></li>
</ul>
</body>
</html>
ผลลัพธ์

ul แรก (ก่อน p) ไม่ได้รับผล | ul ที่ 2 และ 3 (หลัง p) ได้รับ box-shadow สีเขียว
ตัวอย่างที่ 2: img ~ p (p ทุกตัวหลัง 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="https://www.tutorialspoint.com/big_data_analytics/images/big-data-analytics-mini-logo.jpg">
<p>Learn Big Data Analytics at no cost.</p>
</body>
</html>
ผลลัพธ์

p แรก (ก่อน img) ไม่ได้รับผล | p ที่ 2 (หลัง img) ได้พื้นหลังสีน้ำตาลอ่อน
เปรียบเทียบ Sibling Selectors
| Selector | Symbol | เลือก | ตัวอย่าง |
|---|---|---|---|
| Adjacent Sibling | + | พี่น้อง ตัวถัดไปทันที (1 ตัว) | h2 + p - p ตัวแรกหลัง h2 |
| General Sibling | ~ | พี่น้อง ทุกตัว ที่อยู่หลัง | h2 ~ p - p ทุกตัวหลัง h2 |
กรณีใช้งานทั่วไป
- Form validation:
input:invalid ~ .error-message { display: block; } - Tab/Accordion:
input:checked ~ .panel { display: block; } - Progress indicator:
.step.completed ~ .step { opacity: 0.5; } - Feature queries:
.feature-enabled ~ .legacy { display: none; }
ข้อจำกัด
- ต้องมี พาเรนต์เดียวกัน (same parent)
- เลือกได้เฉพาะ พี่น้องที่อยู่หลัง (following siblings) ไม่ใช่พี่น้องก่อนหน้า
- ไม่สามารถเลือก "พี่น้องก่อนหน้า" ได้ (ต้องใช้ :has() หรือ JavaScript)