เราใช้ตัวเลือกพี่น้องที่อยู่ติดกัน (+) หากเราต้องการจับคู่องค์ประกอบที่เกิดขึ้นทันทีหลังจากตัวเลือกแรก ในที่นี้ ตัวเลือกทั้งสองเป็นลูกขององค์ประกอบหลักเดียวกัน
ไวยากรณ์ของ CSS CSS ข้างเคียง combinator มีดังนี้ -
Selector + Selector{
attribute: /*value*/
} หากเราต้องการเลือกพี่น้องของพาเรนต์เดียวกันโดยไม่คำนึงถึงตำแหน่งขององค์ประกอบที่สองที่เลือก เราจะใช้ตัวรวมพี่น้องทั่วไปของ CSS
วากยสัมพันธ์ของ CSS ทั่วไปพี่น้อง combinator มีดังนี้ -
Selector ~ Selector{
attribute: /*value*/
} ตัวอย่างต่อไปนี้แสดงคุณสมบัติ CSS ที่ติดกันและคุณสมบัติตัวผสมแบบพี่น้องทั่วไป
ตัวอย่าง
<!DOCTYPE html>
<html>
<head>
<style>
#parent {
display: flex;
margin: 2%;
padding: 2%;
box-shadow: inset 0 0 24px cyan;
justify-content: space-around;
}
div + p {
font-size: 1.2em;
font-weight: bold;
background: powderblue;
}
section {
box-shadow: 0 0 3px rgba(0,0,0,0.8);
}
</style>
</head>
<body>
<div id="parent">
<img src="https://i.picsum.photos/id/616/200/200.jpg?hmac=QEzyEzU6nVn4d_vdALhsT9UAtTU
EVhwrT-kM5ogBqKM" />
<div>
<p>Check this</p>
<section><p>Some text in section</p></section>
<span>hello</span>
</div>
<p>Selected</p>
</div>
</body>
</html> ผลลัพธ์
สิ่งนี้จะให้ผลลัพธ์ดังต่อไปนี้ -

ตัวอย่าง
<!DOCTYPE html>
<html>
<head>
<style>
#parent {
display: flex;
margin: 2%;
padding: 2%;
background: thistle;
justify-content: space-between;
}
section ~ p {
text-align: center;
font-size: 1.2em;
font-weight: bold;
background: lavender;
}
</style>
</head>
<body>
<div id="parent">
<img src="https://i.picsum.photos/id/616/200/200.jpg?hmac=QEzyEzU6nVn4d_vdALhsT9UAtTU
EVhwrT-kM5ogBqKM" />
<div>
<p>Random text 1</p>
<section><p>Some text in section</p></section>
<span>hello</span>
<p>Selected</p>
</div>
<img src="https://i.picsum.photos/id/1035/200/200.jpg?hmac=IDuYUZQ_7a6h4pQU2k7p2nxTMjMt4uy-p3ze94KtA4" />
</div>
</body>
</html> ผลลัพธ์
สิ่งนี้จะให้ผลลัพธ์ดังต่อไปนี้ -
