CSS :root Selector

Bộ chọn :root là một CSS pseudo-class. Nó khớp với phần tử gốc của tài liệu. Trong tài liệu HTML, đây là phần tử <html>.

Tuy nó hoạt động tương tự bộ chọn html. :root có độ đặc hiệu cao hơn. Thường dùng để xác định kiểu toàn cục hoặc CSS custom properties (variables).

Cú pháp:

:root {
    /* CSS properties */
    background-color: lightgray;
    font-size: 16px;
}

Các kiểu được xác định trong khối :root sẽ áp dụng cho toàn bộ tài liệu. Trừ khi bị ghi đè bởi các quy tắc cụ thể hơn.

Basic Usage Examples

Example 1: Applying a Global Background Color

Ví dụ sau đặt màu nền cho toàn bộ tài liệu. Nó sử dụng bộ chọn :root.

html
<!DOCTYPE html>
<html>

<head>
    <title>root selector</title>
    <style>
        :root {
            background: green;
        }

        body {
            text-align: center;
        }

        h1 {
            color: white;
        }
    </style>
</head>

<body>
    <h1>GeeksforGeeks</h1>
    <h2>:root selector</h2>
    <p>The root of document is body tag</p>
</body>

</html>

Output: css-root-selector

Using the :root Selector for CSS Variables

Bộ chọn :root đặc biệt hữu ích để xác định CSS custom properties (variables). Chúng có thể được sử dụng trên toàn bộ stylesheet để tạo theming nhất quán.

Example: Defining and Using CSS Variables

HTML
<!DOCTYPE html>
<html>

<head>
      <title>Using CSS Variables with :root</title>
    <style>
       :root {
    --main-bg-color: #f0f0f0;
    --main-text-color: #333;
    --primary-color: #4CAF50;
    --font-size: 18px;
}

body {
    background-color: var(--main-bg-color);
    color: var(--main-text-color);
    font-size: var(--font-size);
}

button {
    background-color: var(--primary-color);
    color: white;
    padding: 10px 20px;
    border: none;
    cursor: pointer;
}

button:hover {
    background-color: darkgreen;
}
    </style>
</head>

<body>
    <h1>Themed Webpage Using :root</h1>
    <button>Click Me</button>
</body>

</html>

Output:

css-root-selector
Defining and Using CSS Variables

Supported Browsers:

Các trình duyệt được hỗ trợ bởi bộ chọn :root được liệt kê dưới đây:

  • Apple Safari 1.0 trở lên
  • Google Chrome 1.0 trở lên
  • Edge 12.0 trở lên
  • Firefox 1.0 trở lên
  • Opera 9.5 trở lên

Last Updated : 21/07/2025