|
|
|
|
|
單選按鈕(radio)在網(wǎng)頁設(shè)計中非常常用,但是默認的樣式太死板,用起來體驗不好,而有的人喜歡用圖片結(jié)合JS/CSS來代替,那樣雖然看起來比較好看,但是弄得又過于復(fù)雜了,不易遷移使用。本文給大家介紹一個簡單又漂亮的純CSS單選按鈕(radio)樣式。
從上圖看到,這個單選按鈕的樣式是不錯的,雖然不是那種絢麗炫酷的風(fēng)格,勝在其設(shè)計偏向大眾化但又不失大氣穩(wěn)重,這種風(fēng)格適合大多數(shù)UI的設(shè)計,放到網(wǎng)頁上非常合適。
CSS代碼
body {
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
}
.radio {
margin: 0.5rem;
}
.radio input[type=radio] {
position: absolute;
opacity: 0;
}
.radio input[type=radio] + .radio-label:before {
content: "";
background: #f4f4f4;
border-radius: 100%;
border: 1px solid #b4b4b4;
display: inline-block;
width: 1.4em;
height: 1.4em;
position: relative;
top: -0.2em;
margin-right: 1em;
vertical-align: top;
cursor: pointer;
text-align: center;
transition: all 250ms ease;
}
.radio input[type=radio]:checked + .radio-label:before {
background-color: #3197EE;
box-shadow: inset 0 0 0 4px #f4f4f4;
}
.radio input[type=radio]:focus + .radio-label:before {
outline: none;
border-color: #3197EE;
}
.radio input[type=radio]:disabled + .radio-label:before {
box-shadow: inset 0 0 0 4px #f4f4f4;
border-color: #b4b4b4;
background: #b4b4b4;
}
.radio input[type=radio] + .radio-label:empty:before {
margin-right: 0;
}
HTML代碼
<div class="container">
<div class="radio">
<input id="radio-1" name="radio" type="radio" checked>
<label for="radio-1" class="radio-label">Checked</label>
</div>
<div class="radio">
<input id="radio-2" name="radio" type="radio">
<label for="radio-2" class="radio-label">Unchecked</label>
</div>
<div class="radio">
<input id="radio-3" name="radio" type="radio" disabled>
<label for="radio-3" class="radio-label">Disabled</label>
</div>
</div>
代碼解釋
1、內(nèi)容定位
CSS中 body 的幾行代碼,主要是定位了內(nèi)容區(qū)域的居中作用。display: flex;
是“彈性布局”,它輕易實現(xiàn)內(nèi)容的對齊方式。
2、點擊效果
點擊按鈕后有一個過度切換效果,看起來不顯得突兀,使用體驗提升。實現(xiàn)代碼是這行:
transition: all 250ms ease;
3、增減新項
要添加新的單選按鈕,只需添加一段HTML代碼,無需改變CSS代碼。如下代碼:
<div class="radio">
<input id="radio-4" name="radio" type="radio" >
<label for="radio-4" class="radio-label">demo</label>
</div>
添加HTML代碼,只需更改下 id
的值,這里是第4個單選按鈕,所以是 radio-4
。另外 for
的值也相應(yīng)寫為 radio-4
。這樣我們就可以得到了一個新的單選按鈕。
本文介紹了用純CSS實現(xiàn)簡單又漂亮的CSS單選按鈕(radio)樣式,其特點是風(fēng)格大眾化,適用范圍廣,遷移容易,代碼簡單。