A simple method for styling checkboxes without resorting to non-native solutions.
The checkbox group below:
- Uses native
<input>elements with a type ofcheckboxand programatically associated<label>elements. - Has a styled checkbox that is larger an easier to click than the default-sized checkbox.
- Is achieved by positioning a pseudo-element over the top of the default checkbox, and making sure all functionality still works.
- Has all measurements defined in
emunits so all aspects of the layout will scale together. - Works with short or long lines of content for the label (even though labels should not be as long as the example below).
- Has states defined for:
:hover:focus:checked:checked+:focus
Example
HTML
<div class="example">
<form action="#">
<fieldset class="ch-fieldset">
<legend>Favourite animals?</legend>
<div class="ch-container">
<input class="ch-input" id="frogs" type="checkbox">
<label class="ch-label" for="frogs">Frogs
are cool</label>
</div>
<div class="ch-container">
<input class="ch-input" id="horses" type="checkbox">
<label class="ch-label" for="horses">Horses are
better</label>
</div>
<div class="ch-container">
<input class="ch-input" id="wombats" type="checkbox">
<label class="ch-label" for="wombats">Wombats
are the best, even though they are kinda nasty
and sometimes they can bite</label>
</div>
<div class="ch-container">
<input class="ch-input" id="bats" type="checkbox">
<label class="ch-label" for="bats">Bats are
creepy</label>
</div>
</fieldset>
</form>
</div>
CSS
.example form {
margin: .2em 0 0;
}
fieldset {
margin: 0;
padding: 0;
border: 0;
}
.ch-container {
position: relative;
margin: .7em 0;
line-height: 1.5;
}
.ch-label {
display: block;
padding-left: 1.8em;
color: #555;
}
.ch-input {
position: absolute;
left: .25em;
top: .2em;
font-size: 1em;
cursor: pointer;
}
.ch-input:after {
content: "";
display: block;
position: absolute;
left: -.25em;
top: -.25em;
width: 1em;
height: 1em;
border: .1em solid #7D7D7D;
border-radius: .2em;
background-color: white;
}
.ch-input:hover:after {
border: .1em solid #007000;
}
.ch-input:hover + label {
color: #007000;
}
.ch-input:focus:after {
border: .1em solid black;
box-shadow:
0 0 0 .1em #eee,
0 0 0 .2em #000;
}
.ch-input:focus + label {
color: black;
}
.ch-input:checked + label {
color: black;
}
.ch-input:checked:after {
border: .1em solid blue;
background-color: blue;
background-image: url("../img/tick-01.svg");
background-position: center center;
background-size: 80% 80%;
background-repeat: no-repeat;
}
.ch-input:checked:focus:after {
border: .1em solid black;
background-color: black;
background-image: url("../img/tick-01.svg");
background-position: center center;
background-size: 80% 80%;
background-repeat: no-repeat;
box-shadow:
0 0 0 .1em #fff,
0 0 0 .2em #000;
}
.ch-input:checked:focus + label {
color: black;
}