Giới thiệu
Chúng ta sử dụng bộ chọn anh em liền kề (+) nếu muốn khớp với phần tử xuất hiện ngay lập tức sau bộ chọn đầu tiên. Cả hai bộ chọn đều là con của cùng một phần tử cha.
Cú pháp
Cú pháp của bộ kết hợp anh em liền kề:
Selector + Selector{
attribute: /*giá trị*/
}
Nếu muốn chọn các anh em của cùng một cha bất kể vị trí của phần tử thứ hai, chúng ta sử dụng bộ kết hợp anh em chung (~).
Cú pháp:
Selector ~ Selector{
attribute: /*giá trị*/
}
Ví dụ 1: Adjacent sibling (+)
<!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>
Kết quả
Đoạn mã trên sẽ cho kết quả sau:

Ví dụ 2: General sibling (~)
<!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>
Kết quả
Đoạn mã trên sẽ cho kết quả sau:
