I builded another fork of @klewis’ code sample to demonstrate some playing with pure css and gradients by using :before/:after pseudo elements and a hidden radio input button.
HTML:
sample radio buttons:
<div style="background:lightgrey;">
<span class="radio-item">
<input type="radio" id="ritema" name="ritem" class="true" value="ropt1" checked="checked">
<label for="ritema">True</label>
</span>
<span class="radio-item">
<input type="radio" id="ritemb" name="ritem" class="false" value="ropt2">
<label for="ritemb">False</label>
</span>
</div>
:
CSS:
.radio-item input[type='radio'] {
visibility: hidden;
width: 20px;
height: 20px;
margin: 0 5px 0 5px;
padding: 0;
}
.radio-item input[type=radio]:before {
position: relative;
margin: 4px -25px -4px 0;
display: inline-block;
visibility: visible;
width: 20px;
height: 20px;
border-radius: 10px;
border: 2px inset rgba(150,150,150,0.75);
background: radial-gradient(ellipse at top left, rgb(255,255,255) 0%, rgb(250,250,250) 5%, rgb(230,230,230) 95%, rgb(225,225,225) 100%);
content: "";
}
.radio-item input[type=radio]:checked:after {
position: relative;
top: 0;
left: 9px;
display: inline-block;
visibility: visible;
border-radius: 6px;
width: 12px;
height: 12px;
background: radial-gradient(ellipse at top left, rgb(245,255,200) 0%, rgb(225,250,100) 5%, rgb(75,175,0) 95%, rgb(25,100,0) 100%);
content: "";
}
.radio-item input[type=radio].true:checked:after {
background: radial-gradient(ellipse at top left, rgb(245,255,200) 0%, rgb(225,250,100) 5%, rgb(75,175,0) 95%, rgb(25,100,0) 100%);
}
.radio-item input[type=radio].false:checked:after {
background: radial-gradient(ellipse at top left, rgb(255,225,200) 0%, rgb(250,200,150) 5%, rgb(200,25,0) 95%, rgb(100,25,0) 100%);
}
.radio-item label {
display: inline-block;
height: 25px;
line-height: 25px;
margin: 0;
padding: 0;
}
preview:
https://www.codeply.com/p/y47T4ylfib
Improve Article
Save Article
Improve Article
Save Article
In this article, we are going to discuss how to change the color of the radio button using the accent-color CSS property.
The accent-color property in CSS specifies the color of user interface elements/controls like checkboxes, radio buttons, range, and progress elements. As per this article, we are using this accent-color property to change the color of the radio button from a default color. The syntax and its property values are given below
Syntax:
accent-color : auto | color | initial | inherit;
Property values:
- auto: The browser will set the accent color for the control elements.
- color: It will specify the color for an accent color in RGB representation, hex representation, and also with the color name.
- initial: Sets the accent-color property to the default value.
- inherit: Inherits the property from the parent component.
Note: Depending on the browser the color set by auto property value varies.
Example 1: In the below code, we have created a radio button and specified the color of the radio button using the accent-color property.
HTML
<!DOCTYPE html>
<
html
>
<
head
>
<
style
>
#specifyColor {
accent-color: red;
}
</
style
>
</
head
>
<
body
>
<
center
>
<
h3
> Red colored radio button </
h3
>
<
input
type
=
"radio"
id
=
"specifyColor"
name
=
"radio1"
value
=
"GFG"
>
<
label
for
=
"specifyColor"
>GFG</
label
>
</
center
>
</
body
>
</
html
>
Output:
Example 2: In this example program, we have used various kinds of accent-color properties by specifying the color in different forms like the name of color directly, using RGB color value, hex color code, etc. to change the color of radio buttons.
HTML
<!DOCTYPE html>
<
html
>
<
head
>
<
style
>
input[type=radio]#Yellow {
accent-color: pink;
}
input[type=radio]#Green {
accent-color: rgb(0, 255, 0);
}
input[type=radio]#auto {
accent-color: auto;
}
input[type=radio]#Red {
accent-color: #FF0000;
}
</
style
>
</
head
>
<
body
>
<
center
>
<
h3
> Radio button color change </
h3
>
</
center
>
<
input
type
=
"radio"
id
=
"Yellow"
name
=
"colors"
value
=
"Yellow"
>
<
label
for
=
"Yellow"
>Yellow</
label
><
br
>
<
input
type
=
"radio"
id
=
"Green"
name
=
"colors"
value
=
"Green"
>
<
label
for
=
"Green"
>Green using RGB</
label
><
br
>
<
input
type
=
"radio"
id
=
"auto"
name
=
"colors"
value
=
"auto"
>
<
label
for
=
"auto"
>auto-color set by browser</
label
><
br
>
<
input
type
=
"radio"
id
=
"Red"
name
=
"colors"
value
=
"Red"
>
<
label
for
=
"Red"
>Red color using hex representation
</
label
><
br
>
</
body
>
</
html
>
Output:
В этой статье подробно разберём процесс кастомной стилизации чекбоксов и радиокнопок с помощью CSS.
Как осуществляется создание кастомного чекбокса или переключателя
Данный процесс осуществляется посредством скрытия стандартного элемента и создания с помощью CSS другого «поддельного», такого как мы хотим.
Но как же это будет работать, если стандартный input
скрыть? Это можно выполнить благодаря тому, что в HTML переключить состояние checked
можно не только с помощью самого элемента input
, но и посредством связанного с ним label
.
В HTML связывание label
с input
выполняется одним из 2 способов:
1. Посредством помещения элемента input
в label
:
<label> <input type="checkbox" name="happy" value="yes">Happy </label>
2. Посредством задания элементу input
атрибута id
, а label
– for
с таким же значением как у id
.
<input type="checkbox" id="happy" name="happy" value="yes"> <label for="happy">Happy</label>
В этой статье мы подробно разберём шаги по кастомизации checkbox
и radio
, в которых label
с input
свяжем по 2 варианту. Создание «поддельного» чекбокса выполним с использованием псевдоэлемента ::before
, который поместим в label
. При этом никакие дополнительные элементы в разметку добавлять не будем.
Создание стильного чекбокса
Процесс замены стандартного вида чекбокса на кастомный осуществим посредством выполнения следующей последовательности шагов.
Шаг 1. Создадим разметку.
<input type="checkbox" class="custom-checkbox" id="happy" name="happy" value="yes"> <label for="happy">Happy</label>
При создании разметки очень важно соблюдать последовательность расположения элементов. Это необходимо, потому что в зависимости от того, как они расположены мы будем составлять выражения для выбора элементов в CSS и назначать им стили.
В этом примере элемент label
расположен после input
. Связь label
с input
осуществляется посредством соответствия значения for
элемента label
с id
элемента input
.
В примере к элементу input
добавлен класс custom-checkbox
. Данный класс мы будем использовать при составлении селекторов и тем самым с помощью него определять элементы к которым следует добавить стилизованный чекбокс вместо обычного. Т.е. его присутствие или отсутствие будет определять с каким чекбоксом (со стандартным или поддельным) будет выводится элемент input
с type="checkbox"
.
Шаг 2. Напишем стили для скрытия стандартного элемента input
.
.custom-checkbox { position: absolute; z-index: -1; opacity: 0; }
Мы не будем использовать display: none
, а установим ему стили, с помощью которых уберём его из потока (position: absolute
), поместим его ниже существующих элементов (z-index: -1
), а также сделаем его полностью прозрачным (opacity: 0
). Зачем это нужно? Это нам необходимо для того, чтобы мы могли получить состояние фокуса, а затем стилизовать «подделный» checkbox
или radio
, когда он будет находиться в нём.
Шаг 3. Создадим поддельный чекбокс.
.custom-checkbox+label { display: inline-flex; align-items: center; user-select: none; } .custom-checkbox+label::before { content: ''; display: inline-block; width: 1em; height: 1em; flex-shrink: 0; flex-grow: 0; border: 1px solid #adb5bd; border-radius: 0.25em; margin-right: 0.5em; background-repeat: no-repeat; background-position: center center; background-size: 50% 50%; }
Создание «поддельного» чекбокса выполним с помощью псевдоэлемента ::before
. Посредством CSS зададим ему размеры (в данном случае 1em
x1em
), а затем нарисуем его с помощью border: 1px solid #adb5bd
. Свойства начинающие со слова background
будут определять положение самого флажка (когда checkbox
будет в состоянии checked
).
Первое правило необходимо для вертикального центрирования флажка и надписи к нему. Это действие в примере выполнено через CSS Flexbox.
Шаг 4. Создадим стили при нахождении элемента в состоянии checked
.
.custom-checkbox:checked+label::before { border-color: #0b76ef; background-color: #0b76ef; background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3e%3cpath fill='%23fff' d='M6.564.75l-3.59 3.612-1.538-1.55L0 4.26 2.974 7.25 8 2.193z'/%3e%3c/svg%3e"); }
В этом коде при получении элементом состояния checked
применим к псевдоэлементу ::before
находящемуся в label
стили, посредством которых установим цвет границы, цвет фону и фоновую картинку (флажок) в формате svg.
Шаг 5. Добавим код для стилизации чекбокса при нахождении его в состояниях hover
, active
, focus
и disabled
.
/* стили при наведении курсора на checkbox */ .custom-checkbox:not(:disabled):not(:checked)+label:hover::before { border-color: #b3d7ff; } /* стили для активного состояния чекбокса (при нажатии на него) */ .custom-checkbox:not(:disabled):active+label::before { background-color: #b3d7ff; border-color: #b3d7ff; } /* стили для чекбокса, находящегося в фокусе */ .custom-checkbox:focus+label::before { box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25); } /* стили для чекбокса, находящегося в фокусе и не находящегося в состоянии checked */ .custom-checkbox:focus:not(:checked)+label::before { border-color: #80bdff; } /* стили для чекбокса, находящегося в состоянии disabled */ .custom-checkbox:disabled+label::before { background-color: #e9ecef; }
Открыть пример
Разработка кастомного переключателя
Стилизация переключателя (input
с type="radio"
) выполняется аналогично, т.е. посредством тех же шагов которые мы применяли при кастомизации чекбокса.
Итоговый набор стилей для кастомного оформления input
с type="radio"
:
<style> /* для элемента input c type="radio" */ .custom-radio { position: absolute; z-index: -1; opacity: 0; } /* для элемента label связанного с .custom-radio */ .custom-radio+label { display: inline-flex; align-items: center; user-select: none; } /* создание в label псевдоэлемента before со следующими стилями */ .custom-radio+label::before { content: ''; display: inline-block; width: 1em; height: 1em; flex-shrink: 0; flex-grow: 0; border: 1px solid #adb5bd; border-radius: 50%; margin-right: 0.5em; background-repeat: no-repeat; background-position: center center; background-size: 50% 50%; } /* стили при наведении курсора на радио */ .custom-radio:not(:disabled):not(:checked)+label:hover::before { border-color: #b3d7ff; } /* стили для активной радиокнопки (при нажатии на неё) */ .custom-radio:not(:disabled):active+label::before { background-color: #b3d7ff; border-color: #b3d7ff; } /* стили для радиокнопки, находящейся в фокусе */ .custom-radio:focus+label::before { box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25); } /* стили для радиокнопки, находящейся в фокусе и не находящейся в состоянии checked */ .custom-radio:focus:not(:checked)+label::before { border-color: #80bdff; } /* стили для радиокнопки, находящейся в состоянии checked */ .custom-radio:checked+label::before { border-color: #0b76ef; background-color: #0b76ef; background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3e%3ccircle r='3' fill='%23fff'/%3e%3c/svg%3e"); } /* стили для радиокнопки, находящейся в состоянии disabled */ .custom-radio:disabled+label::before { background-color: #e9ecef; } </style> <input class="custom-radio" name="color" type="radio" id="color-green" value="green"> <label for="color-green">Green</label>
Открыть пример
Ещё примеры по кастомизации checkbox и label
В этом разделе представлены следующие примеры:
- оформление чекбокса, когда input расположен в label
- оформление переключателя, когда input расположен в label
1. Стилизация checkbox, когда input
расположен в label
.
HTML разметка:
<label class="custom-checkbox"> <input type="checkbox" value="value-1"> <span>Indigo</span> </label>
CSS код:
/* для элемента input c type="checkbox" */ .custom-checkbox>input { position: absolute; z-index: -1; opacity: 0; } /* для элемента label, связанного с .custom-checkbox */ .custom-checkbox>span { display: inline-flex; align-items: center; user-select: none; } /* создание в label псевдоэлемента before со следующими стилями */ .custom-checkbox>span::before { content: ''; display: inline-block; width: 1em; height: 1em; flex-shrink: 0; flex-grow: 0; border: 1px solid #adb5bd; border-radius: 0.25em; margin-right: 0.5em; background-repeat: no-repeat; background-position: center center; background-size: 50% 50%; } /* стили при наведении курсора на checkbox */ .custom-checkbox>input:not(:disabled):not(:checked)+span:hover::before { border-color: #b3d7ff; } /* стили для активного чекбокса (при нажатии на него) */ .custom-checkbox>input:not(:disabled):active+span::before { background-color: #b3d7ff; border-color: #b3d7ff; } /* стили для чекбокса, находящегося в фокусе */ .custom-checkbox>input:focus+span::before { box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25); } /* стили для чекбокса, находящегося в фокусе и не находящегося в состоянии checked */ .custom-checkbox>input:focus:not(:checked)+span::before { border-color: #80bdff; } /* стили для чекбокса, находящегося в состоянии checked */ .custom-checkbox>input:checked+span::before { border-color: #0b76ef; background-color: #0b76ef; background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3e%3cpath fill='%23fff' d='M6.564.75l-3.59 3.612-1.538-1.55L0 4.26 2.974 7.25 8 2.193z'/%3e%3c/svg%3e"); } /* стили для чекбокса, находящегося в состоянии disabled */ .custom-checkbox>input:disabled+span::before { background-color: #e9ecef; }
Открыть пример
2. Стилизация radio
, когда input
расположен в label
.
HTML разметка:
<label class="custom-radio"> <input type="radio" name="color" value="indigo"> <span>Indigo</span> </label>
CSS код:
/* для элемента input c type="radio" */ .custom-radio>input { position: absolute; z-index: -1; opacity: 0; } /* для элемента label связанного с .custom-radio */ .custom-radio>span { display: inline-flex; align-items: center; user-select: none; } /* создание в label псевдоэлемента before со следующими стилями */ .custom-radio>span::before { content: ''; display: inline-block; width: 1em; height: 1em; flex-shrink: 0; flex-grow: 0; border: 1px solid #adb5bd; border-radius: 50%; margin-right: 0.5em; background-repeat: no-repeat; background-position: center center; background-size: 50% 50%; } /* стили при наведении курсора на радио */ .custom-radio>input:not(:disabled):not(:checked)+span:hover::before { border-color: #b3d7ff; } /* стили для активной радиокнопки (при нажатии на неё) */ .custom-radio>input:not(:disabled):active+span::before { background-color: #b3d7ff; border-color: #b3d7ff; } /* стили для радиокнопки, находящейся в фокусе */ .custom-radio>input:focus+span::before { box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25); } /* стили для радиокнопки, находящейся в фокусе и не находящейся в состоянии checked */ .custom-radio>input:focus:not(:checked)+span::before { border-color: #80bdff; } /* стили для радиокнопки, находящейся в состоянии checked */ .custom-radio>input:checked+span::before { border-color: #0b76ef; background-color: #0b76ef; background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3e%3ccircle r='3' fill='%23fff'/%3e%3c/svg%3e"); } /* стили для радиокнопки, находящейся в состоянии disabled */ .custom-radio>input:disabled+span::before { background-color: #e9ecef; }
Открыть пример
There are two approaches to styling checkboxes and radio buttons with CSS. For a simple way to match the colour of the standard controls to your site’s design, you can use the accent-color
property. For complete control over the design of checkboxes and radio buttons, you can use the appearance
property to disable their standard styling and implement your own.
Setting an accent colour
The accent-color
property sets the colour used by checkboxes and radio buttons, as well as range fields and progress indicators. The accent colour is inherited, so only needs to be set at the root of the document:
|
|
The accent-color
property is currently supported by Firefox, Chrome, and Edge, and will be supported in the next version of Safari. These checkboxes and radio buttons are styled using accent-color
:
A fully custom design
The design of checkboxes and radio buttons styled using the accent-color
property varies between browsers and operating systems, and may not work well with the rest of your site’s design. As an alternative, you can use the appearance
property to disable the standard styling and implement a fully custom design, as these checkboxes and radio buttons do:
Creating the boxes
Firstly we style the default state of the controls (enabled, but not active, focused, or checked):
|
|
Lines 2 and 3 disable the standard styling by setting the appearance
property to none
(the -webkit-appearance
property is needed for Safari).
Lines 4 and 5 set the size of the controls. While we would usually use relative units to scale user interface controls based on the text size, for checkboxes and radio buttons this can lead to controls that are too small or excessively large, so we instead use a reasonable fixed size. Note that we are assuming the use of border box sizing, so these dimensions include the border width.
Lines 6 and 7 align the controls with their label text. The vertical-align
property isn’t precise enough on its own, so we combine it with a margin on the top of half the line height (here 1.5em
) minus half the widget height, which centres the controls within the line. We also add some margin on the right to create more space between the control and its label.
Lines 8, 9, and 14 set the borders of the controls. Checkboxes are given slightly rounded corners, while radio buttons are made circular. Line 10 sets the background, including the positioning of the images that we will add later.
Active and focused states
Next we style the active and focused states, which are essential for visitors who use the keyboard to interact with sites:
|
|
The change in border colour clearly indicates the active or focused element, so we can disable the default outline. Note that we add :not(:disabled)
to the :active
selector as otherwise disabled controls would show as active while the mouse is held down on them.
Disabled state
Next we style the disabled state by greying out the controls:
|
|
Checked state
Finally we style the checked state using background images:
|
|
You can download checkbox.svg (148 bytes) and radio.svg (137 bytes) for use on your own site.
The finished code
Combining all of the above leads to the finished code:
|
|
Sharing styling with other input controls
Other input controls usually share elements of their design — such as borders and active, focus, and disabled styling — with checkboxes and radio buttons:
In this case, the shared styling can be set for all controls (lines 1 to 18), reducing the amount of additional styling needed for checkboxes and radio buttons (lines 20 to 39):
|
|
Is it possible to change the background color of a radio button input in Firefox/Chrome like in IE? (Without using images)
Run this in both IE(<9) and Firefox/Chrome:
input[type="radio"] {
background: red;
}
<input type="radio" /> RadioButton
View on JSFiddle
showdev
28k36 gold badges53 silver badges72 bronze badges
asked Jul 12, 2011 at 10:18
0
Add this attribute to your radio input selector
input[type="radio"]{
accent-color:green;
}
answered Jan 12, 2022 at 20:03
Alternatively it is possible to change the border using CSS.
This is the input radio:
<input name="myinput" id="myinput" type="radio" value="1" class="highlighted" />
And this is the CSS:
.highlighted {
outline:1px solid #F00; /* Firefox, Opera, Chrome, IE8+ */
*filter: progid:DXImageTransform.Microsoft.dropshadow(OffX=-1, OffY=0,color=#FF0000) progid:DXImageTransform.Microsoft.dropshadow(OffX=1, OffY=0,color=#FF0000) progid:DXImageTransform.Microsoft.dropshadow(OffX=0, OffY=-1,color=#FF0000) progid:DXImageTransform.Microsoft.dropshadow(OffX=0, OffY=1,color=#FF0000); /* IE6, IE7 */
}
answered Sep 24, 2011 at 3:04
The short answer is «no».
Even if you do manage to get something that works in one browser, browsers tend to handle form controls very differently, meaning it’s nigh impossible to achieve cross-browser compatibility.
Disappointing, I know. Check out this article for more info: http://www.456bereastreet.com/archive/200409/styling_form_controls/
Just by the way, why do you want to change the background color? Generally a radio button background will just pick up the background color of its container.
answered Jul 1, 2013 at 9:14
LukeLuke
4,4631 gold badge30 silver badges37 bronze badges
I know this is an old question bit it still comes up quite high if you google the question so here is my solution.
Style a <label>
element that is directly after the radio button.
HTML
<input type=radio name="colour" value="green" id="colour-green" /><label for="colour-green" ></label>
<input type=radio name="colour" value="red" id="colour-red" /><label for="colour-red" ></label>
<input type=radio name="colour" value="blue" id="colour-blue" /><label for="colour-blue" ></label>
CSS
input[type=radio]{
display:none;
}
input[type=radio] + label{
border: 1px solid black;
background-color: red;
border-radius: 50%;
display: block;
...
}
input[type=radio]:checked + label{
background-color: green;
}
answered Oct 30, 2017 at 17:08
To change the background color of a radio button input Only in IE
HTML
<input type="radio" name="custom">
<input type="radio" name="custom">
CSS
input[type=radio] {
width: 20px;
height: 20px;
}
/* This will make the border gray when the button is not checked. */
input[type=radio]:not(:checked)::-ms-check {
border-color: gray;
}
input[type=radio]::-ms-check {
border-color: red; /* This will make the border red when the button is checked. */
color: red; /* This will make the circle red when the button is checked. */
}
answered Aug 29, 2018 at 12:07
Try this:
.your-class { accent-color: red; mix-blend-mode: multiply; }
answered Sep 28, 2022 at 7:00
input radio is just a circle, so you can change the style of the < a > or < div > tag like this:
Here
answered Jul 12, 2011 at 10:43
MaidotMaidot
3864 silver badges11 bronze badges
3
Is it possible to change the background color of a radio button input in Firefox/Chrome like in IE? (Without using images)
Run this in both IE(<9) and Firefox/Chrome:
input[type="radio"] {
background: red;
}
<input type="radio" /> RadioButton
View on JSFiddle
showdev
28k36 gold badges53 silver badges72 bronze badges
asked Jul 12, 2011 at 10:18
0
Add this attribute to your radio input selector
input[type="radio"]{
accent-color:green;
}
answered Jan 12, 2022 at 20:03
Alternatively it is possible to change the border using CSS.
This is the input radio:
<input name="myinput" id="myinput" type="radio" value="1" class="highlighted" />
And this is the CSS:
.highlighted {
outline:1px solid #F00; /* Firefox, Opera, Chrome, IE8+ */
*filter: progid:DXImageTransform.Microsoft.dropshadow(OffX=-1, OffY=0,color=#FF0000) progid:DXImageTransform.Microsoft.dropshadow(OffX=1, OffY=0,color=#FF0000) progid:DXImageTransform.Microsoft.dropshadow(OffX=0, OffY=-1,color=#FF0000) progid:DXImageTransform.Microsoft.dropshadow(OffX=0, OffY=1,color=#FF0000); /* IE6, IE7 */
}
answered Sep 24, 2011 at 3:04
The short answer is «no».
Even if you do manage to get something that works in one browser, browsers tend to handle form controls very differently, meaning it’s nigh impossible to achieve cross-browser compatibility.
Disappointing, I know. Check out this article for more info: http://www.456bereastreet.com/archive/200409/styling_form_controls/
Just by the way, why do you want to change the background color? Generally a radio button background will just pick up the background color of its container.
answered Jul 1, 2013 at 9:14
LukeLuke
4,4631 gold badge30 silver badges37 bronze badges
I know this is an old question bit it still comes up quite high if you google the question so here is my solution.
Style a <label>
element that is directly after the radio button.
HTML
<input type=radio name="colour" value="green" id="colour-green" /><label for="colour-green" ></label>
<input type=radio name="colour" value="red" id="colour-red" /><label for="colour-red" ></label>
<input type=radio name="colour" value="blue" id="colour-blue" /><label for="colour-blue" ></label>
CSS
input[type=radio]{
display:none;
}
input[type=radio] + label{
border: 1px solid black;
background-color: red;
border-radius: 50%;
display: block;
...
}
input[type=radio]:checked + label{
background-color: green;
}
answered Oct 30, 2017 at 17:08
To change the background color of a radio button input Only in IE
HTML
<input type="radio" name="custom">
<input type="radio" name="custom">
CSS
input[type=radio] {
width: 20px;
height: 20px;
}
/* This will make the border gray when the button is not checked. */
input[type=radio]:not(:checked)::-ms-check {
border-color: gray;
}
input[type=radio]::-ms-check {
border-color: red; /* This will make the border red when the button is checked. */
color: red; /* This will make the circle red when the button is checked. */
}
answered Aug 29, 2018 at 12:07
Try this:
.your-class { accent-color: red; mix-blend-mode: multiply; }
answered Sep 28, 2022 at 7:00
input radio is just a circle, so you can change the style of the < a > or < div > tag like this:
Here
answered Jul 12, 2011 at 10:43
MaidotMaidot
3864 silver badges11 bronze badges
3
Styling native radio input elements cross-browser is a bit more painful than it should be. Over the years, lots and lots of blogs have discussed this topic and provided various styling workarounds. Most solutions involve showing additional pseudo elements such as
[type=radio]:checked::before,
[type=checkbox]:checked::before {
content: "";
width: 14px;
height: 14px;
background-color: #ffa500;
position: absolute;
top: 2px;
left: 2px;
}
Modern CSS to the rescue
With some simple and modern CSS, we can now style radio button input
elements even easier. Below are three different options, each having its pros and cons. You can try out the different options in the CodePen below.
See the Pen
Styled radio buttons by Bryntum (@bryntum)
on CodePen.
Using accent-color
The CSS property accent-color styles some native elements by changing their accent color. This property is widely supported in 2022. But it is not fully supported and most browsers only started supporting it in 2021.
body {
accent-color: red;
}
Pros
- Simple to use
Cons
- Low stylability
- Not fully supported
Using box-shadow
Both the box-shadow and the outline solutions are accomplished by hiding the native appearance of the element. And then with a combination of background, border and an outer circle, we create a new appearance which will is easier to style.
input {
/* The native appearance is hidden */
appearance: none;
-webkit-appearance: none;
/* For a circular appearance we need a border-radius. */
border-radius: 50%;
/* The background will be the radio dot's color. */
background: #FF572233;
/* The border will be the spacing between the dot and the outer circle */
border: 3px solid #FFF;
/* And by creating a box-shadow with no offset and no blur, we have an outer circle */
box-shadow: 0 0 0 1px #FF5722;
}
Note that in some cases the box-shadow can be clipped by it’s container. In these cases, a margin can be a good solution.
Pros
- Full support
- High stylability
Cons
- Scales badly in some environments.
Using outline
The outline solution applies the same technique as the box-shadow solution, but creates the outer circle using the outline property instead. Outline is widely supported, but not in combination with border-radius which does not work as expected in Safari.
Note that the outline is the browser’s default focus style. When changing the outline style, you should always have accessibility in mind.
input {
appearance: none;
-webkit-appearance: none;
border-radius: 50%;
background: #e8e8e8;
border: 3px solid #FFF;
/* The outline will be the outer circle */
outline: 1px solid #999;
}
Pros
- Scales better than box-shadow
- High stylability
- Does not affect layout
Cons
- No Safari support.
Which one to choose?
In the upcoming 5.1 release, we at Bryntum decided to use the `box-shadow` option in our Radio button widget. It provides a reliable cross-browser appearance and it is compatible with a bit older browsers. You can see this in action in our conflict resolution dialog in the Scheduler Pro.