In part 2 of my series of styling form fields using only CSS, we look at checkboxes. The approach and elements will be very similar to how we styled radio buttons – again we’ll be hiding the actual form element and focus on styling the label and adding some pseudo elements to achieve the desired effect …
As ever, we start with some basic markup …
<form action="">
<fieldset>
<legend>Checkboxes</legend>
<p><input type="checkbox" name="checkbox-set" id="checkbox-1" value="Normal Checkbox" checked= /><label for="checkbox-1">Normal Checkbox 1</label></p>
<p><input type="checkbox" name="checkbox-set" id="checkbox-2" value="Normal Checkbox" /><label for="checkbox-2">Normal Checkbox 2</label></p>
<p><input type="checkbox" name="checkbox-set" id="checkbox-3" value="Normal Checkbox" required= /><label for="checkbox-3">Normal Checkbox 3</label></p>
<p><input type="checkbox" name="checkbox-set" id="checkbox-4" value="Normal Checkbox" disabled= /><label for="checkbox-4">Disabled Checkbox</label></p>
</fieldset>
</form>
Checkboxes
See the Pen Form with unstyled checkboxes by Jacques Mostert (@jayx) on CodePen.14523
As per my previous, we hide the checkboxes and use the fields’ label
and some pseudo elements for the actual styling …
body{
font-family: Arial, Helvetica, sans-serif;
}
/* Set up the label basics */
label{
display: inline-block;
font-size: 1em;
height: 2em;
line-height: 2em;
vertical-align: middle;
}
/* Hide the checkboxes */
input[type="checkbox"]{
display: none;
}
… next we set up some space for the faux checkbox
…
/* Set up some space for the faux checkbox */
input[type="checkbox"] + label{
padding: 0 0 0 1.5em;
position: relative;
}
… then we set up the empty checkbox container with a pseudo element …
/* Set up the empty checkbox container */
input[type="checkbox"] + label::before{
background: #fff;
border: 2px solid #333;
border-radius: 20%;
content: "";
display: inline-block;
height: 1em;
left: 0;
position: absolute;
top: calc(0.5em - 2px);
width: 1em;
}
… next we add the tick marks for selected boxes – you can use unicode characters for this (✓ or ✔), use an icon font or use another pseudo element/empty box with borders on 2 sides and transform
it like I did …
/* Set up the check/tick marks */
input[type="checkbox"]:checked + label::after{
background: transparent;
border-bottom: 3px solid #0b79bf;
border-left: 3px solid #0b79bf;
content: "";
display: inline-block;
height: 0.4em;
left: 0.25em;
position: absolute;
top: 0.5em;
transform: rotate(-20deg) skewX(-10deg);
width: 1em;
}
… and don’t forget to set up disabled styles …
/* Set up disabled styles */
input[type="checkbox"]:disabled + label{
color: #999;
}
input[type="checkbox"]:disabled + label:before{
border-color: #999;
}
That’s it – we’re done!
See the Pen Form with custom styled checkboxes by Jacques Mostert (@jayx) on CodePen.14523
As ever – comments are open … have your say, ask some questions, always play nice.