Как сделать обязательный чекбокс html. Убираем input, оформляем спаны. Теги чекбокса и радиокнопки находятся внутри тега

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

Input:checked + label:before { content: "\2022"; color: #f3f3f3; font-size: 30px; text-align: center; line-height: 18px; }

Теперь когда мы нажмём на радио кнопку, в основном сером круге должен появиться маленький белый кружок.

Стилизуем чекбоксы

Теперь давайте займёмся оформление чекбоксов. Для начала снова спрячем элемент:

Input { display: none; }

Поскольку мы убираем стандартное отображение чекбокса при помощи псевдо-элемента:before, просто добавим рамку:

Checkbox label:before { border-radius: 3px; }

Затем добавим символ “галочка”, который появится при клике по чекбоксу. Сделаем это по аналогии с радиокругом. На этот раз нам понадобится преобразовать HTML символ? ✓.

Input:checked + label:before { content: "\2713"; text-shadow: 1px 1px 1px rgba(0, 0, 0, .2); font-size: 15px; color: #f3f3f3; text-align: center; line-height: 15px; }

В итоге, вот что у нас должно получиться:

Итоги

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

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 (

Top