Next-sibling combinator

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

Bộ kết hợp anh em liền kề (+) phân tách hai bộ chọn và khớp với phần tử thứ hai chỉ khi nó liền ngay sau phần tử đầu tiên, và cả hai đều là con của cùng một element cha.

css
/* Paragraphs that come immediately after any image */
img + p {
  font-weight: bold;
}

Cú pháp

css
/* The white space around the + combinator is optional but recommended. */
former_element + target_element { style properties }

Ví dụ

Cách sử dụng cơ bản

Ví dụ này minh họa cách chọn anh em liền kề nếu anh em liền kề đó thuộc một kiểu cụ thể.

CSS

Chúng ta chỉ tạo kiểu cho <li> liền ngay sau một <li> là phần tử đầu tiên trong kiểu của nó:

css
li:first-of-type + li {
  color: red;
  font-weight: bold;
}

HTML

html
<ul>
  <li>One</li>
  <li>Two!</li>
  <li>Three</li>
</ul>

Kết quả

Chọn anh em liền trước

Bộ kết hợp anh em liền kề có thể được bao gồm trong bộ chọn hàm :has() để chọn anh em liền trước.

CSS

Chúng ta chỉ tạo kiểu cho <li> có anh em liền kế là một <li> cuối cùng trong kiểu của nó:

css
li:has(+ li:last-of-type) {
  color: red;
  font-weight: bold;
}

HTML

html
<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three!</li>
  <li>Four</li>
</ul>

Kết quả

Thông số kỹ thuật

Thông số kỹ thuật
Selectors Level 4
# adjacent-sibling-combinators

Khả năng tương thích với trình duyệt

Xem thêm