如何使用 CSS 更改單選按鈕的顏色?


使用 CSS 更改單選按鈕的顏色是一個簡單的過程,可以透過多種方法實現。在本文中,我們將學習和了解兩種不同的方法來使用 CSS 更改單選按鈕的顏色。

單選按鈕允許從多個可用選項中選擇一個選項。在本文中,我們有一個單選按鈕,我們的任務是使用 CSS 更改單選按鈕的顏色。

更改單選按鈕顏色的方法

以下是使用 CSS 更改單選按鈕顏色的方法列表,我們將在本文中逐步解釋並提供完整的示例程式碼。

使用 accent-color 屬性更改單選按鈕顏色

在這種更改單選按鈕顏色方法中,我們使用了 accent-color 屬性,該屬性用於指定 UI 元素(如單選按鈕、複選框等)的顏色。

  • 我們使用了 "input[type="radio"] {}" CSS 選擇器 來選擇單選按鈕。
  • 在第二步中,我們使用了 "accent-color: green;" 屬性,它將單選按鈕的顏色更改為綠色。

示例

這是一個完整的示例程式碼,實現了上述步驟來更改單選按鈕的顏色。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        Changing color of the radio button using CSS
    </title>
    <style>
        body {
            text-align: center;
        }    
        input[type="radio"] {
            accent-color: green;
        }
    </style>
</head>
    <body>
        <h3>
            Change the color of radio buttons using CSS
        </h3>
        <p>
            In this example we have used accent-color
            property to Change the color of radio button
            using CSS.
        </p>
        <input type="radio" id="RadioButton" 
               name="RadioButton" value="RadioButton">
        <label for="RadioButton">Radio Button</label>
    </body>
</html>

使用 hue-rotate() 濾鏡更改單選按鈕顏色

為了使用 CSS 更改單選按鈕的顏色,我們使用了 hue-rotate() 濾鏡,它應用一個濾鏡來設定色調旋轉,透過根據您想要的顏色更改引數中指定的度數來實現。

  • 我們使用了 "input[type="radio"] {}" CSS 選擇器來選擇單選按鈕。
  • 在第二步中,我們使用了 "filter: hue-rotate(270deg);" 濾鏡,它將單選按鈕的顏色更改為綠色。
  • 由於單選按鈕的預設顏色是 藍色(色調角度為 210 度),而綠色的 色調角度為 120 度,因此我們可以使用 -90 度或 270 度將其顏色更改為綠色。

示例

這是一個完整的示例程式碼,實現了上述步驟來更改單選按鈕的顏色。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        Changing color of the radio button using CSS
    </title>
    <style>
        body {
            text-align: center;
        }    
        input[type="radio"] {
            filter: hue-rotate(270deg);
        }
    </style>
</head>
    <body>
        <h3>
            Change the color of radio buttons using CSS
        </h3>
        <p>
            In this example we have used hue-rotate()
            filter to Change the color of radio button
            using CSS.
        </p>
        <input type="radio" id="RadioButton" 
               name="RadioButton" value="RadioButton">
        <label for="RadioButton">Radio Button</label>
    </body>
</html>

結論

在本文中,我們瞭解瞭如何使用 CSS 更改單選按鈕的顏色。我們討論了兩種不同的更改單選按鈕顏色方法:使用 accent-color 屬性和使用 hue-rotate() 濾鏡。我們可以使用以上兩種方法中的任何一種。

更新於: 2024-07-19

25K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.