Checkbox значение по умолчанию. Стилизуем чекбоксы и радиокнопки с CSS3

25.05.2019

Сегодня я покажу вам классный прием, который позволит создавать классные чекбоксы, гораздо более красивые, чем те, что предлагает html по умолчанию. Я покажу, как делается в css оформление checkbox -ов. Иными словами, я покажу вам, как сделать на css красивые чекбоксы (checkbox), то есть галочки.

Начальная разметка

Итак, начать нужно с того, чтобы добавить в html код, который выведет наши чекбоксы, а также подписи к ним (label), эти поля нужно связать между собой, чтобы при клике на label можно было устанавливать галочку в поле.

Так, я немного прокомментирую. У нас есть три пары: поле checkbox и подпись к нему. Каждое поле получает свой идентификатор, связка с лейблом происходит с помощью атрибута for , где прописывается имя идентификатора, с которым нужно связать. Пока на странице все выглядит так, то есть это обычный внешний вид чекбоксов. Сейчас мы будем его изменять.

Убираем input, оформляем спаны

Итак, теперь нам надо скрыть со страницы обычные чекбоксы.

Input { display:none; }

Теперь нужно как-то оформить новые поля. Оформлять мы будем элементы span, так как они находятся внутри label .

Input + label span{ display:inline-block; width:40px; margin-right: 10px; height:40px; vertical-align:middle; border: 5px solid green; cursor:pointer; border-radius: 5px; }

Этим селектором мы выбрали все спаны в лейблах, которые находятся в коде сразу за input ами с типом checkbox . Таким образом, оформление применится к нашим спанам. Мы даем им блочно-строчный тип, определенную ширину и высоту, отступ справа, чтобы текст не прилегал вплотную.

Делаем так, чтобы все заработало

Теперь нужно сделать так, чтобы при клике внутри спана, то есть при выборе какого-то варианта, в него автоматом ставилась галочка. Для этого я для начала нашел в интернете соответствующую иконку с галочкой (она должна быть в формате png), уменьшил ее до размеров нашего поля. Теперь остается вставить такой код:

Input:checked + label span{ background:url(btn.png) no-repeat; }

Все, теперь работает! Попробуйте пощелкать и вы увидите, что при выборе появляется красивая галочка. Моя картинка лежала в той же папке, что и файл css и называлась btn.png , отсюда и такая запись.

Ну а что же делает наш волшебный селектор input:checked + label span ? По сути, он приказывает браузеру следующее: когда любой из чекбоксов будет отмечен, примени для спанов в лейблах фоновую картинку. Вот так вот все просто, мы обошлись без скриптов, сделав красивые чекбоксы на чистом css. Пишите в комментарии, если что-то непонятно.

Для того, чтобы оформить чекбоксы и радиокнопки, как того требует дизайн, сегодня не обязательно использовать JavaScript-решения (типа моего плагина ), т.к. для этого можно задействовать только CSS, причем с обратной совместимостью для старых браузеров (т.е. не в ущерб юзабилити), которые не поддерживают современные CSS-правила.

Другими словами — в современных браузерах чекбоксы и радиокнопки будут выглядеть красиво, в соответствии с задуманным дизайном, а в старых (это относится к Internet Explorer версии 8 и ниже ) они останутся с оформлением «по умолчанию», характерным для каждой конкретной операционной системы.

Кроме того, сохраняется возможность HTML5-валидации стилизуемых элементов (чего может не быть при использовании JavaScript-плагинов). В современных браузерах ее поддержка — уже давно норма.

Важные особенности

Чтобы всё получилось, важно учитывать следующее:

  1. Кроме, собственно, самого тега элемента, который мы хотим красиво оформить ( или ), понадобится тег
  2. Тег должен находиться до тега

«Фокус» заключается в использовании псевдоселекторов:checked и:not . При этом сам чекбокс или радиокнопка делаются невидимыми, а их эмуляция осуществляется с помощью псевдоэлементов:before и:after для тега

Стилизация для современных браузеров

Рассмотрим оба вариант расположения стилизуемого элемента формы. Какой из них наиболее удобен — решать вам. Суть от этого не меняется.

Теги чекбокса и радиокнопки находятся перед тегом

В HTML-коде это выглядит следующим образом:

Еще раз хочу заострить ваше внимание — тег обязательно должен быть расположен перед тегом

CSS-код для чекбокса будет таким:

Checkbox { position: absolute; z-index: -1; opacity: 0; margin: 10px 0 0 20px; } .checkbox + label { position: relative; padding: 0 0 0 60px; cursor: pointer; } .checkbox + label:before { content: ""; position: absolute; top: -4px; left: 0; width: 50px; height: 26px; border-radius: 13px; background: #CDD1DA; box-shadow: inset 0 2px 3px rgba(0,0,0,.2); transition: .2s; } .checkbox + label:after { content: ""; position: absolute; top: -2px; left: 2px; width: 22px; height: 22px; border-radius: 10px; background: #FFF; box-shadow: 0 2px 5px rgba(0,0,0,.3); transition: .2s; } .checkbox:checked + label:before { background: #9FD468; } .checkbox:checked + label:after { left: 26px; } .checkbox:focus + label:before { box-shadow: inset 0 2px 3px rgba(0,0,0,.2), 0 0 0 3px rgba(255,255,0,.7); }

CSS-код для радиокнопки будет таким:

Radio { position: absolute; z-index: -1; opacity: 0; margin: 10px 0 0 7px; } .radio + label { position: relative; padding: 0 0 0 35px; cursor: pointer; } .radio + label:before { content: ""; position: absolute; top: -3px; left: 0; width: 22px; height: 22px; border: 1px solid #CDD1DA; border-radius: 50%; background: #FFF; } .radio + label:after { content: ""; position: absolute; top: 1px; left: 4px; width: 16px; height: 16px; border-radius: 50%; background: #9FD468; box-shadow: inset 0 1px 1px rgba(0,0,0,.5); opacity: 0; transition: .2s; } .radio:checked + label:after { opacity: 1; } .radio:focus + label:before { box-shadow: 0 0 0 3px rgba(255,255,0,.7); }

С помощью свойств position , z-index и opacity для классов.checkbox и.radio мы визуально прячем оригинальные элементы, при этом они остаются на том же самом месте, где будут стилизованные элементы. А с помощью margin немного смещаем их, чтобы сообщение валидации HTML5 смотрелось гармонично. В зависимости от дизайна чекбокса и радиокнопки этот отступ можно подогнать.

Теги чекбокса и радиокнопки находятся внутри тега

HTML-код в данном случае будет следующим:

Я переключаю чекбокс

По аналогии с предыдущим вариантом — тег обязательно должен быть расположен перед тегами с классом.checkbox__text и.radio__text .

CSS-код для чекбокса будет таким:

Checkbox input { position: absolute; z-index: -1; opacity: 0; margin: 10px 0 0 20px; } .checkbox__text { position: relative; padding: 0 0 0 60px; cursor: pointer; } .checkbox__text:before { content: ""; position: absolute; top: -4px; left: 0; width: 50px; height: 26px; border-radius: 13px; background: #CDD1DA; box-shadow: inset 0 2px 3px rgba(0,0,0,.2); transition: .2s; } .checkbox__text:after { content: ""; position: absolute; top: -2px; left: 2px; width: 22px; height: 22px; border-radius: 10px; background: #FFF; box-shadow: 0 2px 5px rgba(0,0,0,.3); transition: .2s; } .checkbox input:checked + .checkbox__text:before { background: #9FD468; } .checkbox input:checked + .checkbox__text:after { left: 26px; } .checkbox input:focus + .checkbox__text:before { box-shadow: inset 0 2px 3px rgba(0,0,0,.2), 0 0 0 3px rgba(255,255,0,.7); }

CSS-код для радиокнопки будет таким:

Radio input { position: absolute; z-index: -1; opacity: 0; margin: 10px 0 0 7px; } .radio__text { position: relative; padding: 0 0 0 35px; cursor: pointer; } .radio__text:before { content: ""; position: absolute; top: -3px; left: 0; width: 22px; height: 22px; border: 1px solid #CDD1DA; border-radius: 50%; background: #FFF; } .radio__text:after { content: ""; position: absolute; top: 1px; left: 4px; width: 16px; height: 16px; border-radius: 50%; background: #9FD468; box-shadow: inset 0 1px 1px rgba(0,0,0,.5); opacity: 0; transition: .2s; } .radio input:checked + .radio__text:after { opacity: 1; } .radio input:focus + .radio__text:before { box-shadow: 0 0 0 3px rgba(255,255,0,.7); }

Стили здесь те же самые, что и в предыдущем способе, только они применяются для других селекторов.

Стилизация с учетом старых браузеров

CSS-код для чекбокса . В комментариях к коду я добавил пояснения касательно браузеров:

/* Cначала обозначаем стили для IE8 и более старых версий т.е. здесь мы немного облагораживаем стандартный чекбокс. */ .checkbox { vertical-align: top; width: 17px; height: 17px; margin: 0 3px 0 0; } /* Это для всех браузеров, кроме совсем старых, которые не поддерживают селекторы с плюсом. Показываем, что label кликабелен. */ .checkbox + label { cursor: pointer; } /* Далее идет оформление чекбокса в современных браузерах, а также IE9 и выше. Благодаря тому, что старые браузеры не поддерживают селекторы:not и:checked, в них все нижеследующие стили не сработают. В данном случае checked указывается без двоеточия впереди, почему-то это срабатывает именно так. */ .checkbox:not(checked) { position: absolute; z-index: -1; opacity: 0; margin: 10px 0 0 20px; } .checkbox:not(checked) + label { position: relative; padding: 0 0 0 60px; } .checkbox:not(checked) + label:before { content: ""; position: absolute; top: -4px; left: 0; width: 50px; height: 26px; border-radius: 13px; background: #CDD1DA; box-shadow: inset 0 2px 3px rgba(0,0,0,.2); transition: .2s; } .checkbox:not(checked) + label:after { content: ""; position: absolute; top: -2px; left: 2px; width: 22px; height: 22px; border-radius: 10px; background: #FFF; box-shadow: 0 2px 5px rgba(0,0,0,.3); transition: .2s; } .checkbox:checked + label:before { background: #9FD468; } .checkbox:checked + label:after { left: 26px; } .checkbox:focus + label:before { box-shadow: inset 0 2px 3px rgba(0,0,0,.2), 0 0 0 3px rgba(255,255,0,.7); }

CSS-код для радиокнопки :

Radio { vertical-align: top; width: 17px; height: 17px; margin: 0 3px 0 0; } .radio + label { cursor: pointer; } .radio:not(checked) { position: absolute; z-index: -1; opacity: 0; margin: 10px 0 0 7px; } .radio:not(checked) + label { position: relative; padding: 0 0 0 35px; } .radio:not(checked) + label:before { content: ""; position: absolute; top: -3px; left: 0; width: 22px; height: 22px; border: 1px solid #CDD1DA; border-radius: 50%; background: #FFF; } .radio:not(checked) + label:after { content: ""; position: absolute; top: 1px; left: 4px; width: 16px; height: 16px; border-radius: 50%; background: #9FD468; box-shadow: inset 0 1px 1px rgba(0,0,0,.5); opacity: 0; transition: .2s; } .radio:checked + label:after { opacity: 1; } .radio:focus + label:before { box-shadow: 0 0 0 3px rgba(255,255,0,.7); }

Примеры

Вот таким несложным образом это и делается. Благодаря данному способу, оформить чекбоксы и радиокнопки с помощью CSS можно так, как вам будет угодно.

Note: Unlike other input controls, a checkboxes value is only included in the submitted data if the checkbox is currently checked . If it is, then the value of the checkbox"s value attribute is reported as the input"s value.

Using checkbox inputs

We already covered the most basic use of checkboxes above. Let"s now look at the other common checkbox-related features and techniques you"ll need.

Handling multiple checkboxes

The example we saw above only contained one checkbox; in real-world situations you"ll be likely to encounter multiple checkboxes. If they are completely unrelated, then you can just deal with them all separately, as shown above. However, if they"re all related, things are not quite so simple.

For example, in the following demo we include multiple checkboxes to allow the user to select their interests (see the full version in the section).

Choose your interests

In this example you will see that we"ve given each checkbox the same name (note the brackets at the end of the name, which allows the values to be sent as an array). If both checkboxes are checked and then the form is submitted, you"ll get a string of name/value pairs submitted like this: interest=coding&interest=music . When this data reaches the server-side, you should be able to capture it as an array of related values and deal with it appropriately - see Handle Multiple Checkboxes with a Single Serverside Variable , for example.

Checking boxes by default

To make a checkbox checked by default, you simply give it the checked attribute. See the below example:

Choose your interests

Providing a bigger hit area for your checkboxes

In the above examples, you may have noticed that you can toggle a checkbox by clicking on its associated element represents a caption for an item in a user interface.">

Beyond accessibility, this is another good reason to properly set up

Indeterminate state checkboxes

In addition to the checked and unchecked states, there is a third state a checkbox can be in: indeterminate . This is a state in which it"s impossible to say whether the item is toggled on or off. This is set using the elements."> HTMLInputElement object"s indeterminate property via JavaScript (it cannot be set using an HTML attribute):

InputInstance.indeterminate = true;

A checkbox in the indeterminate state has a horizontal line in the box (it looks somewhat like a hyphen or minus sign) instead of a check/tick in most browsers.

There are not many use cases for this property. The most common is when a checkbox is available that "owns" a number of sub-options (which are also checkboxes). If all of the sub-options are checked, the owning checkbox is also checked, and if they"re all unchecked, the owning checkbox is unchecked. If any one or more of the sub-options have a different state than the others, the owning checkbox is in the indeterminate state.

Examples

The following example is an extended version of the "multiple checkboxes" example we saw above - it has more standard options, plus an "other" checkbox that when checked causes a text field to appear to enter a value for the "other" option. This is achieved with a simple block of JavaScript. The example also includes some CSS to improve the styling.

HTML

Choose your interests

CSS

html { font-family: sans-serif; } form { width: 600px; margin: 0 auto; } div { margin-bottom: 10px; } fieldset { background: cyan; border: 5px solid blue; } legend { padding: 10px; background: blue; color: cyan; }

JavaScript

var otherCheckbox = document.querySelector("input"); var otherText = document.querySelector("input"); otherText.style.visibility = "hidden"; otherCheckbox.onchange = function() { if(otherCheckbox.checked) { otherText.style.visibility = "visible"; otherText.value = ""; } else { otherText.style.visibility = "hidden"; } };

Specifications

Specification Status Comment
HTML Living Standard
The definition of "" in that specification.
Living Standard
HTML5
The definition of "" in that specification.
Recommendation

Browser compatibility

The compatibility table on this page is generated from structured data. If you"d like to contribute to the data, please check out

Opera for Android Safari on iOS Samsung Internet type="checkbox" Chrome Full support Yes Edge Full support Yes Firefox Full support Yes IE Full support Yes Opera Full support Yes Safari Full support Yes WebView Android Full support Yes Chrome Android Full support Yes Edge Mobile Full support Yes Firefox Android Full support 4 Opera Android Full support Yes Safari iOS Full support Yes Samsung Internet Android ?

Legend

Full support Full support Compatibility unknown Compatibility unknown

See also

  • element is used to create interactive controls for web-based forms in order to accept data from the user; a wide variety of types of input data and control widgets are available, depending on the device and user agent."> and the elements."> HTMLInputElement interface which implements it.
  • The ), checkbox (), or option (