如何設定單選按鈕選中標籤的樣式?
在這篇文章中,我們將為當前選中的單選按鈕設定標籤樣式。CSS 還允許您消除預設的單選按鈕,並設定標籤的選中和未選中狀態的樣式。這將藉助 :checked偽類來實現。此外,還將使用相鄰兄弟選擇器來實現此效果。
設定單選按鈕選中標籤的樣式
首先,我們將原始圓形單選按鈕的display 屬性設定為 none,使其從檢視中消失。接下來,我們將為未選中狀態的標籤元素應用預設樣式。我們將標籤的 display 屬性設定為inline-block,並應用其他樣式,如背景、內邊距、字型和游標。
現在,使用:checked 偽類以及相鄰兄弟選擇器 (+)。此選擇器特別有助於確保樣式僅應用於選中單選輸入後的標籤。
示例程式碼
在程式碼示例中,您可以看到我們稍微調整了樣式,使單選按鈕更具吸引力。您可以嘗試自己的樣式使其更具吸引力。
<!DOCTYPE html>
<html>
<head>
<title>Styled Radio Button Labels</title>
<style>
body,
html {
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
background-color: #f5f5f5;
font-family: Arial, sans-serif;
}
.radio-container {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.radio-container input[type="radio"] {
opacity: 0;
width: 0;
position: fixed;
}
.radio-container label {
display: inline-block;
background-color: #e0e0e0;
padding: 8px 16px;
font-size: 16px;
cursor: pointer;
margin-right: 8px;
border-radius: 4px;
transition: all 0.3s ease;
}
.radio-container input[type="radio"]:checked + label {
background-color: #4caf50;
color: #fff;
box-shadow: 0 2px 4px rgba(76, 175, 80, 0.3);
}
.radio-container label:hover {
background-color: #dcdcdc;
transform: translateY(-1px);
}
.radio-container input[type="radio"]:focus + label {
outline: 2px solid #4caf50;
outline-offset: 2px;
}
/* Adding responsive design */
@media (max-width: 480px) {
.radio-container {
display: flex;
flex-direction: column;
gap: 10px;
}
.radio-container label {
margin-right: 0;
text-align: center;
}
}
</style>
</head>
<body>
<div class="radio-container">
<input type="radio" id="option1" name="options" checked>
<label for="option1">Full Stack</label>
<input type="radio" id="option2" name="options">
<label for="option2">Front-End</label>
<input type="radio" id="option3" name="options">
<label for="option3">Back-End</label>
</div>
</body>
</html>
輸出

廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP