Css radio buttons and checkboxes

Styling checkboxes and radio buttons with CSS

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):

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 
input:where([type="checkbox"], [type="radio"])  -webkit-appearance : none;  appearance : none;  width : 22px;  height : 22px;  margin : calc(0.75em - 11px) 0.25rem 0 0;  vertical-align : top;  border : 2px solid #ddd;  border-radius : 4px;  background : #fff no-repeat center center; >  input[type="radio"]  border-radius : 50%; >

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:

input:where([type="checkbox"], [type="radio"]):where(:active:not(:disabled), :focus)  border-color : #696;  outline : none; >

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:

input:where([type="checkbox"], [type="radio"]):disabled  background : #eee; >

Checked state

Finally we style the checked state using background images:

input[type="checkbox"]:checked  background-image : url('checkbox.svg'); >  input[type="radio"]:checked  background-image : url('radio.svg'); >

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:

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 
input:where([type="checkbox"], [type="radio"])  -webkit-appearance : none;  appearance : none;  width : 22px;  height : 22px;  margin : calc(0.75em - 11px) 0.25rem 0 0;  vertical-align : top;  border : 2px solid #ddd;  border-radius : 4px;  background : #fff no-repeat center center; >  input[type="radio"]  border-radius : 50%; >  input:where([type="checkbox"], [type="radio"]):where(:active:not(:disabled), :focus)  border-color : #696;  outline : none; >  input:where([type="checkbox"], [type="radio"]):disabled  background : #eee; >  input[type="checkbox"]:checked  background-image : url('checkbox.svg'); >  input[type="radio"]:checked  background-image : url('radio.svg'); >

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):

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 
input, textarea, select  border : 2px solid #ddd;  border-radius : 4px;  background : #fff no-repeat center center;  color : #000; >  :is(input, textarea, select):where(:active:not(:disabled), :focus)  border-color : #696;  outline : none; >  :is(input, textarea, select):disabled  background : #eee;  color : #000; >  input:where([type="checkbox"], [type="radio"])  -webkit-appearance : none;  appearance : none;  width : 22px;  height : 22px;  margin : calc(0.75em - 11px) 0.25rem 0 0;  vertical-align : top; >  input[type="radio"]  border-radius : 50%; >  input[type="checkbox"]:checked  background-image : url('checkbox.svg'); >  input[type="radio"]:checked  background-image : url('radio.svg'); >

Источник

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

Для того, чтобы оформить чекбоксы и радиокнопки, как того требует дизайн, сегодня не обязательно использовать JavaScript-решения (типа моего плагина jQuery Form Styler), т.к. для этого можно задействовать только CSS, причем с обратной совместимостью для старых браузеров (т.е. не в ущерб юзабилити), которые не поддерживают современные CSS-правила. Другими словами — в современных браузерах чекбоксы и радиокнопки будут выглядеть красиво, в соответствии с задуманным дизайном, а в старых (это относится к Internet Explorer версии 8 и ниже) они останутся с оформлением «по умолчанию», характерным для каждой конкретной операционной системы. Кроме того, сохраняется возможность HTML5-валидации стилизуемых элементов (чего может не быть при использовании JavaScript-плагинов). В современных браузерах ее поддержка — уже давно норма.

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

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

«Фокус» заключается в использовании псевдоселекторов :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

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

С помощью свойств 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

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

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

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

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

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

Примеры

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

Смотрите также

  • jQuery Form Styler — плагин для стилизации элементов HTML-форм (input[type=checkbox], input[type=radio], input[type=file], input[type=number], select) 2614 комментариев
  • Верстка красивых тегов для сайта + бонус 25 комментариев
  • Зеленый свет CSS-свойствам при верстке под IE8 и выше 26 комментариев
  • jQuery-плагин для стилизации input[type=»radio»] 38 комментариев

Источник

Читайте также:  Css появление блока при нажатии
Оцените статью