26. Combinator trong CSS

Combinator trong CSS: combinator là cách bạn kết hợp các selec­tor để chọn các phần tử mục tiêu dựa trên mối quan hệ cấu trúc hoặc vị trí của chúng trong cây DOM. Có một số loại combinator khác nhau, bao gồm descendant combinator, child combinator, adjacent sibling combinator và general sibling combinator.

Dưới đây là một số ví dụ về cách sử dụng các loại combinator khác nhau:

HTML:

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="styles.css">
  <title>Combinator Example</title>
</head>
<body>
  <div class="container">
    <div class="parent">
      <p>Parent Paragraph</p>
      <div class="child">
        <p>Child Paragraph</p>
        <p>Another Child Paragraph</p>
      </div>
    </div>
    <p class="sibling">Adjacent Sibling</p>
    <p class="general-sibling">General Sibling</p>
  </div>
</body>
</html>

CSS (styles.css):

css
.parent p {
  color: blue; /* Select tất cả các phần tử <p> nằm trong .parent */
}

.parent > p {
  font-weight: bold; /* Select các phần tử <p> trực tiếp con của .parent */
}

.sibling + .general-sibling {
  background-color: yellow; /* Select .general-sibling ngay sau .sibling */
}

Trong ví dụ này, chúng ta có các phần tử và combinator khác nhau:

  1. .parent p: Sử dụng descendant combinator để chọn tất cả các phần tử <p> nằm trong .parent.
  2. .parent > p: Sử dụng child combinator để chọn các phần tử <p> trực tiếp con của .parent.
  3. .sibling + .general-sibling: Sử dụng adjacent sibling combinator để chọn phần tử có class .general-sibling ngay sau phần tử có class .sibling.

Các combinator giúp bạn chọn và áp dụng kiểu cho các phần tử cụ thể trong cấu trúc của trang web dựa trên mối quan hệ giữa chúng trong DOM.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top