CSS element~element Selector

Bộ chọn element ~ element trong CSS được dùng để chọn phần tử thứ hai. Phần tử này theo sau phần tử thứ nhất (không cần liền kề). Cả hai phải có cùng phần tử cha.

Cú pháp:

element ~ element {
//CSS Property
}

Ví dụ 1: Bạn có thể thấy "p ~ ul" sẽ chọn và tạo kiểu cho danh sách không thứ tự thứ hai. Danh sách này nằm sau đoạn văn và không phải danh sách đầu tiên.

html
<!DOCTYPE html>
<html>
  
<head>
    <title>
        CSS element ~ element Selector
    </title>
    <style>
        p~ul {
            color: white;
            background: green;
        }
    </style>
</head>

<body style="">
    <h2 style="color:green; 
               text-align: center;">
        CSS element ~ element Selector
    </h2>

    <div>Searching algorithms</div>
    <ul>
        <li>Binary search</li>
        <li>Linear search</li>
    </ul>

    <p>Sorting Algorithms</p>
    <ul>
        <li>Merge sort</li>
        <li>Quick sort</li>
    </ul>
</body>
  
</html>

Output: css-elementelement-selector-3Ví dụ 2: 

HTML
<!DOCTYPE html>
<html>
  
<head>
    <title>
        CSS element ~ element Selector
    </title>
    <style>
        p~span {
            color: white;
            background: green;
        }
    </style>
</head>

<body style="">
    <!--<h1 style = "color:green;text-align: center;">-->
    <!-- GeeksforGeeks-->
    <!--</h1>-->
    <h2 style="color:green; 
               text-align: center;">
        CSS element ~ element Selector
    </h2>
    <span>This is the first span.</span>
    <p>This is the first paragraph.</p>
    <code>Some code</code>
    <span>A computer science </span>
    <code>More code.....</code>
    <span> portal for geeks.</span>
</body>
  
</html>

Output: css-elementelement-selector-3Trình duyệt được hỗ trợ: Các trình duyệt được hỗ trợ bởi bộ chọn element ~ element được liệt kê dưới đây:

  • Apple Safari 3.2
  • Google Chrome 4.0
  • Firefox 3.5
  • Opera 9.6

Last Updated : 21/07/2025