CSS :only-of-type Selector

Trong CSS, selector :only-of-type chỉ chọn những phần tử không có anh chị em cùng loại. Nó được dùng để thiết lập thuộc tính CSS cho phần tử đó.

Cú pháp:

:only-of-type {
// CSS property
}

Ví dụ 1: Trong ví dụ này, chúng ta sẽ sử dụng selector đã được giải thích ở trên.

html
<!DOCTYPE html>
<html>

<head>
    <title>:only-of-type selector</title>
    <style>
        h1 {
            color: green;
        }

        body {
            text-align: center;
        }

        p:only-of-type {
            color: green;
            font-size: 25px;
        }
    </style>
</head>

<body>
    <h1>GeeksforGeeks</h1>
    <h2>:only-of-type selector</h2>
    <div>
        <p>Single child of its parent</p>
    </div>
    <div>
        <p>Child 1 of its parent</p>
        <p>Child 2 of its parent</p>
    </div>
</body>

</html>

Đầu ra:

css-only-of-type-selector

Ví dụ 2:

html
<!DOCTYPE html>
<html>

<head>
    <title>:only-of-type selector</title>
    <style>
        h1 {
            color: green;
        }

        body {
            text-align: center;
        }

        input:only-of-type {
            background-color: green;
            border: 1px solid black;
            color: white;
            text-align: center;
        }
    </style>
</head>

<body>
    <h1>GeeksforGeeks</h1>
    <h2>:only-of-type selector</h2>
    <div>
        <input type="text" value="Only child">
    </div><br>
    <div>
        <input type="text" value="Child 1 of its parent">
        <input type="text" value="Child 2 of its parent">
    </div>
</body>

</html>

Đầu ra:

css-only-of-type-selector

Trình duyệt được hỗ trợ: Danh sách trình duyệt hỗ trợ selector :only-of-type như sau:

  • Chrome 1.0
  • Edge 12.0
  • Opera 9.5
  • Firefox 3.5
  • Safari 3.1

Last Updated : 21/07/2025