Стилизация Checkbox
Несколько примеров как изменить внешний вид чекбоксов с помощью CSS, изображений и немного JS.
Метод «Checkbox Hack»
Основан на связи
Стоит заменить что в некоторых старых браузерах (например Safari) такой приём не работает и требует добавление атрибутов for у и id у чекбокса.
В зависимости от состояния чекбокса :checked , :disabled и :focus , следующему за ним элементу, например , можно задавать стили с помощью селектора « + ».
/* Dafault */ label input[type=checkbox] + span < . >/* Focus */ label input[type=checkbox]:focus + span < . >/* Checked */ label input[type=checkbox]:checked + span < . >/* Disabled */ label input[type=checkbox]:disabled + span < . >label input[type=checkbox]:disabled:checked + span
Сам чекбокс скрывается, но без использования display: none , что бы оставить функциональность фокуса.
label input[type=checkbox]
По умолчанию, фокус появляется при клике на элемент, что не очень и нужно. Оставить выделение при фокусе только при нажатии клавиши Tab можно с помощью JQuery, добавляя класс focused родительскому элементу.
$(window).keyup(function(e) < var target = $('label input[type=checkbox]:focus'); if (e.keyCode == 9 && $(target).length)< $(target).parent().addClass('focused'); >>); $('label input[type=checkbox]').focusout(function()< $(this).parent().removeClass('focused'); >);
Пример №1
В первом примере понадобятся два изображения (обычный и отмеченный), для ускорения прорисовки можно использовать спрайты, но тогда не сделать плавную смену при переключении ( transition background ).

HTML-разметка:
Фокус по клавише Tab:
$(window).keyup(function(e) < var target = $('.checkbox-other input:focus'); if (e.keyCode == 9 && $(target).length)< $(target).parent().addClass('focused'); >>); $('.checkbox-other input').focusout(function()< $(this).parent().removeClass('focused'); >);
CSS-стили:
.checkbox-other < display: block; margin: 0 0 10px 0; cursor: pointer; user-select: none; position: relative; >.checkbox-other input[type=checkbox] < position: absolute; z-index: -1; opacity: 0; display: block; width: 0; height: 0; >.checkbox-other span < display: inline-block; position: relative; padding: 0 0 0 35px; line-height: 22px; >.checkbox-other span:before < content: ""; display: inline-block; width: 22px; height: 22px; position: absolute; left: 0; top: 0; transition: background 0.3s ease; background: url(/checkbox-1.png) 0 0 no-repeat; >/* Checked */ .checkbox-other input[type=checkbox]:checked + span:before < background-image: url(/checkbox-2.png); >/* Focus */ .focused span:before < box-shadow: 0 0 0 0.2rem rgba(0,123,255,.25); >/* Hover */ .checkbox-other span:hover:before < filter: brightness(110%); >/* Active */ .checkbox-other span:active:before < filter: brightness(80%); >/* Disabled */ .checkbox-other input[type=checkbox]:disabled + span < color: #666; cursor: default; >.checkbox-other input[type=checkbox]:disabled + span:before
Результат:
Пример №2
Подходит для случаев, когда галка выходит за края элемента. HTML-разметка и JS-код остается прежними.


.checkbox-other < display: block; margin: 0 0 10px 0; cursor: pointer; user-select: none; position: relative; >.checkbox-other input[type=checkbox] < position: absolute; z-index: -1; opacity: 0; display: block; width: 0; height: 0; >.checkbox-other span < display: inline-block; position: relative; padding: 0 0 0 35px; line-height: 22px; >.checkbox-other span:before < content: ""; display: inline-block; width: 22px; height: 22px; position: absolute; left: 0; top: 0; background: url(/checkbox-3.png) 0 0 no-repeat; >/* Checked */ .checkbox-other input[type=checkbox] + span:after < content: ""; opacity: 0; transition: opacity 0.3s ease; >.checkbox-other input[type=checkbox]:checked + span:after < display: inline-block; width: 22px; height: 22px; position: absolute; left: 4px; top: -5px; background: url(/checkbox-4.png) 0 0 no-repeat; opacity: 1; >/* Focus */ .focused span:before < box-shadow: 0 0 0 0.2rem rgba(0,123,255,.25); >/* Hover */ .checkbox-other span:hover:after < filter: brightness(110%); >/* Active */ .checkbox-other span:active:before, .checkbox-other span:active:after < filter: brightness(80%); >/* Disabled */ .checkbox-other input[type=checkbox]:disabled + span < color: #666; cursor: default; >.checkbox-other input[type=checkbox]:disabled + span:before, .checkbox-other input[type=checkbox]:disabled + span:after
CSS оформление чекбокса (checkbox)
Так как input стилизовать нельзя, мы будем его скрывать и стилизовать span.
One Two Three Four html разметка
.container < display: block; position: relative; padding-left: 35px; margin-bottom: 12px; cursor: pointer; font-size: 22px; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; >.container input < position: absolute; opacity: 0; cursor: pointer; height: 0; width: 0; >.checkmark < position: absolute; top: 0; left: 0; height: 25px; width: 25px; background-color: white; border: 1px solid grey; >.container:hover input~.checkmark < background-color: #ccc; >.container input:checked~.checkmark < background-color: orange; border: 1px solid orange; >.checkmark:after < content: ""; position: absolute; display: none; >.container input:checked~.checkmark:after < display: block; >.container .checkmark:after
How to Style a Checkbox with CSS
A checkbox is one of the HTML forms used on every website, but mostly they are not styled and look the same. If you want to make your site more attractive, you can style the checkboxes. If you don’t know how to do that, let’s create a sample together, step by step using only CSS.
Watch a video course CSS — The Complete Guide (incl. Flexbox, Grid & Sass)
Create HTML
html> html> head> title>Title of the document title> head> body> section> h2>How to style checkbox h2> div class="checkbox-example"> input type="checkbox" value="1" id="checkboxOneInput"/> label for="checkboxOneInput"> label> div> section> body> html>
Add CSS
- Hide the checkboxes by setting the visibility property to its “hidden” value.
- Use the :checked pseudo-class, which helps to see when the checkbox is checked.
- Style the label with the width, height, background, margin, and border-radius properties. Set the position to «relative».
- Style the «checkbox-example» class by setting the display to «block» and specifying the width and height properties. Then, specify the border-radius , transition, position, and other properties.
- Now the slider is in the unchecked position. To move the slider button, we need to know whether the checkbox is checked. When it is checked, we must change the left property of the label element. We use the + combinator to select the label sibling, just next to it.
/* Start by hiding the checkboxes*/ input[type=checkbox] < visibility: hidden; > input[type="checkbox"]:checked < some code goes here > /* the slider bar */ .checkbox-example < width: 45px; height: 15px; background: #555; margin: 20px 80px; position: relative; border-radius: 5px; > /* the slider from the label */ .checkbox-example label < display: block; width: 18px; height: 18px; border-radius: 50%; transition: all .5s ease; cursor: pointer; position: absolute; top: -2px; left: -3px; background: #ccc; > /* Move the slider if the checkbox is clicked */ .checkbox-example input[type=checkbox]:checked+label < left: 27px; >
Now we will combine all these in one code and will have our checkbox ready.
Example of styling a checkbox with CSS:
html> html> head> title>Title of the document title> style> input[type=checkbox] < visibility: hidden; > .checkbox-example < width: 45px; height: 15px; background: #555; margin: 20px 10px; position: relative; border-radius: 5px; > .checkbox-example label < display: block; width: 18px; height: 18px; border-radius: 50%; transition: all .5s ease; cursor: pointer; position: absolute; top: -2px; left: -3px; background: #ccc; > .checkbox-example input[type=checkbox]:checked + label < left: 27px; > style> head> body> h2>How to style checkbox h2> section> div class="checkbox-example"> input type="checkbox" value="1" id="checkboxOneInput" /> label for="checkboxOneInput"> label> div> section> body> html>
Result
We can also use the CSS :after and :before pseudo selectors to add ticks or crosses or any other supplementary UI.
Example of using a styled checkbox:
html> html> head> style> .main < display: block; position: relative; padding-left: 45px; margin-bottom: 15px; cursor: pointer; font-size: 20px; > h1 < color: orange; > /* Hiding the initial checkbox */ input[type=checkbox] < visibility: hidden; > /* Creating a custom checkbox based on demand */ .w3docs < position: absolute; top: 0; left: 0; height: 25px; width: 25px; background-color: black; > /* Specify the background color to be shown when hovering over checkbox */ .main:hover input ~ .w3docs < background-color: gray; > /* Specify the background color to be shown when checkbox is active */ .main input:active ~ .w3docs < background-color: white; > /* Specify the background color to be shown when checkbox is checked */ .main input:checked ~ .w3docs < background-color: orange; > /* Checkmark to be shown in checkbox */ /* It is not be shown when not checked */ .w3docs:after < content: ""; position: absolute; display: none; > /* Display checkmark when checked */ .main input:checked ~ .w3docs:after < display: block; > /* Styling the checkmark using webkit */ /* Rotated the rectangle by 45 degree and showing only two border to make it look like a tickmark */ .main .w3docs:after < left: 8px; bottom: 5px; width: 6px; height: 12px; border: solid white; border-width: 0 4px 4px 0; -webkit-transform: rotate(45deg); -ms-transform: rotate(45deg); transform: rotate(45deg); > style> head> body> h1> Learn to design and build professional website h1> label class="main">CodeX input type="checkbox"> span class="w3docs"> span> label> label class="main">W3Docs input type="checkbox" checked="checked"> span class="w3docs"> span> label> label class="main">CodeY input type="checkbox"> span class="w3docs"> span> label> body> html>
Example of styling a checkbox using CSS properties:
html> html> head> title>Style a checkbox using CSS title> style> h1 < color: #8ebf42; > .script < display: block; position: relative; padding-left: 45px; margin-bottom: 15px; cursor: pointer; font-size: 20px; > /* Hide the default checkbox */ input[type=checkbox] < visibility: hidden; > /* creating a custom checkbox based on demand */ .w3docs < position: absolute; top: 0; left: 0; height: 25px; width: 25px; background-color: black; > /* specify the background color to be shown when hovering over checkbox */ .script:hover input ~ .w3docs < background-color: orange; > /* specify the background color to be shown when checkbox is active */ .script input:active ~ .w3docs < background-color: red; > /* specify the background color to be shown when checkbox is checked */ .script input:checked ~ .w3docs < background-color: black; > /* checkmark to be shown in checkbox */ /* It is not be shown when not checked */ .w3docs:after < content: ""; position: absolute; display: none; > /* display checkmark when checked */ .script input:checked ~ .w3docs:after < display: block; > /* styling the checkmark using webkit */ /* creating a square to be the sign of checkmark */ .script .w3docs:after < left: 6px; bottom: 5px; width: 6px; height: 6px; border: solid white; border-width: 4px 4px 4px 4px; > style> head> body> h1>Do you like W3Docs? h1> label class="script" style="color:black;"> Yes input type="checkbox"> span class="w3docs"> span> label> label class="script" style="color:black;"> Yes Of course input type="checkbox" checked="checked"> span class="w3docs"> span> label> body> html>
How TO — Custom Checkbox
Learn how to create custom checkboxes and radio buttons with CSS.
Default:
Custom checkbox:
One Two Three Four
Custom radio button:
One Two Three Four
How To Create a Custom Checkbox
Step 1) Add HTML:
Example
Step 2) Add CSS:
Example
/* Customize the label (the container) */
.container display: block;
position: relative;
padding-left: 35px;
margin-bottom: 12px;
cursor: pointer;
font-size: 22px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
>
/* Hide the browser’s default checkbox */
.container input position: absolute;
opacity: 0;
cursor: pointer;
height: 0;
width: 0;
>
/* Create a custom checkbox */
.checkmark position: absolute;
top: 0;
left: 0;
height: 25px;
width: 25px;
background-color: #eee;
>
/* On mouse-over, add a grey background color */
.container:hover input ~ .checkmark background-color: #ccc;
>
/* When the checkbox is checked, add a blue background */
.container input:checked ~ .checkmark background-color: #2196F3;
>
/* Create the checkmark/indicator (hidden when not checked) */
.checkmark:after content: «»;
position: absolute;
display: none;
>
/* Show the checkmark when checked */
.container input:checked ~ .checkmark:after display: block;
>
/* Style the checkmark/indicator */
.container .checkmark:after left: 9px;
top: 5px;
width: 5px;
height: 10px;
border: solid white;
border-width: 0 3px 3px 0;
-webkit-transform: rotate(45deg);
-ms-transform: rotate(45deg);
transform: rotate(45deg);
>
How To Create a Custom Radio Button
Example
/* Customize the label (the container) */
.container display: block;
position: relative;
padding-left: 35px;
margin-bottom: 12px;
cursor: pointer;
font-size: 22px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
>
/* Hide the browser’s default radio button */
.container input position: absolute;
opacity: 0;
cursor: pointer;
height: 0;
width: 0;
>
/* Create a custom radio button */
.checkmark position: absolute;
top: 0;
left: 0;
height: 25px;
width: 25px;
background-color: #eee;
border-radius: 50%;
>
/* On mouse-over, add a grey background color */
.container:hover input ~ .checkmark background-color: #ccc;
>
/* When the radio button is checked, add a blue background */
.container input:checked ~ .checkmark background-color: #2196F3;
>
/* Create the indicator (the dot/circle — hidden when not checked) */
.checkmark:after content: «»;
position: absolute;
display: none;
>
/* Show the indicator (dot/circle) when checked */
.container input:checked ~ .checkmark:after display: block;
>
/* Style the indicator (dot/circle) */
.container .checkmark:after top: 9px;
left: 9px;
width: 8px;
height: 8px;
border-radius: 50%;
background: white;
>
