Sonntag, 20. Juli 2014

Use a font for form check boxes! ... CSS based.

Native form check boxes suffer some disadvantages. They:
  1. are not cross browser consistent (Safari, Chrome, Opera or Firefox)
  2. are not scaleable
  3. are not fully styleable (and therefore may not fit to the look and feel of the page)
Native web form check boxes could look like:
The check boxes above are built on:
with some CSS:
div.checkboxes input[type=checkbox]{
  float: left;
  margin-right: 1em;
}
div.checkboxes label{
  display: block;
  margin: 0.5em;
}
Compare the native look and feel with the CSS font based only solution:
Since the check box font solution is based on CSS styles only, the HTML structure is still the same (except the input elements have the additional CSS class 'hidden'), but with some additional CSS:
@font-face {
  font-family: 'FontAwesome';
  src: url(/assets/fontawesome-webfont.eot?v=4.1.0);
  src: url(/assets/fontawesome-webfont.eot?#iefix&v=4.1.0) format("embedded-opentype"), 
    url(/assets/fontawesome-webfont.woff?v=4.1.0) format("woff"),   
    url(/assets/fontawesome-webfont.ttf?v=4.1.0) format("truetype"), 
    url(/assets/fontawesome-webfont.svg?v=4.1.0#fontawesomeregular) format("svg");
  font-weight: normal;
  font-style: normal;
} 
.hidden{
  display: none;
}
div.checkboxes input[type=checkbox].hidden + label:before{
  font-family: FontAwesome;
  font-size: 1.5em;
  font-style: normal;  
  cursor: pointer;
}
div.checkboxes input[type=checkbox].hidden + label:before{
  content: "\f096";
  margin-right: 1em;
  position: relative;
  top: 0.2em;
}
div.checkboxes input[type=checkbox].hidden:checked + label:before{
  content: '\f046';
  color: #A00000;
}
div.checkboxes input[type=checkbox].hidden:hover + label:before{
  font-size: 2em;
}
div.checkboxes input[type=checkbox].hidden:active + label:before{
  text-shadow: 0px 0px 5px #666;
}
In the example the awesome font 'Awesome' was used.
It is important to include the font into the page with '@font-face'. That forces the clients to download the font once (after the font was downloaded the clients are considered to hold it in their cache).
Please note, that the check box inputs are hidden, but still existing.
Furthermore the font content is styled before the label by using the pseudo class ':before'. In combination with the state of the check box by using the CSS3 pseudo class ':checked' the content is overridden.
All following styles are just for improving the user experience, although this is pretty subjective and can vary depending on the use case.
The technique can be applied to other form controls as well, like radio buttons.

Firefox 21+, Chrome 21+, Safari 5.1+, Opera 12.1+, IE 9+, Android browser 2.3+, iOS Safari 6.0+, Opera min 5.0+

Keine Kommentare:

Kommentar veröffentlichen