Чекбоксы - это что такое? Стилизация чекбоксов и радиокнопок на чистом CSS с совместимостью для старых браузеров

09.07.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. Пишите в комментарии, если что-то непонятно.

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 (
Похожие статьи