CSS :root 選擇器



CSS 中的 :root 選擇器是一個偽類,它匹配文件樹的根元素。對於 HTML 文件,:root 代表 <html> 元素本身,因此此選擇器與 html 元素選擇器相同。但 :root 選擇器比 HTML 元素選擇器具有更高的特異性。

語法

/* Selects the root element (<html>) of the document */
:root {
    // css variable declarations or properties
}

宣告全域性 CSS 變數

根選擇器的主要目的是在 CSS 中宣告 變數。這將允許在樣式表中的所有選擇器中全域性訪問。讓我們看一個例子。

示例

<!DOCTYPE html>
<html>

<head>
    <style>
        :root {
        --main-color: blue;
        --secondary-color: white;
        }
        body {
        background-color: var(--main-color);
        }
        h1 {
        color: var(--secondary-color);
        }
    </style>
</head>

<body>
    <h1>Welcome to CSS Root Example</h1>
    <p> 
        This is an example of using CSS root to define and use 
        custom CSS variables.
    </p>
</body>

</html>

支援的瀏覽器

選擇器 Chrome Edge Firefox Safari Opera
:root 4.0 9.0 3.5 3.2 9.6
css_properties_reference.htm
廣告