Styling Checkboxes with CSS only (no images)
Styling Checkboxes with CSS Only (no images), using the :checked pseudo selector.
by prince bazawule
September 13, 2017
HTML
<p>
Which of these genres are do you listen to? (check 'em out if you don't already.)
</p>
<span class="check_box_group">
<input type="checkbox" id="breakbeat" name="my_checkbox" value="breakbeat">
<label for="breakbeat"><span>breakbeat</span></label><br>
<input type="checkbox" id="dnb" name="my_checkbox" value="dnb">
<label for="dnb"><span>drum&bass</span></label><br>
<input type="checkbox" id="jungle" name="my_checkbox" value="jungle">
<label for="jungle"><span>jungle</span></label>
</span>
SCSS
// variables
// colors
$white: rgba(254, 255, 250, 1);
$grey: rgba(220, 231, 235, 1);
$lightgrey: rgba(220, 231, 235, 0.25);
$darkgrey: rgba(192, 200, 208, 1);
$blue: rgba(34, 190, 198, 1);
$black: rgba(48, 69, 92, 0.8);
// fonts
$sans: 'Ubuntu', sans-serif;
$heading: 'Source Sans Pro', sans-serif;
// document styles
body {
position: relative;
width: 90%;
height: 100%;
background: $lightgrey;
font-family: $sans;
font-weight: 300;
color: $black;
margin: 5% auto;
p {
margin-bottom: 1em;
}
}
// checkbox group
.check_box_group {
position: relative;
padding: 0;
// hide checkbox input
input[type="checkbox"] {
display: none;
// style span within the label
& + label span {
position: relative;
display: inline-block;
vertical-align: middle;
cursor: pointer;
margin-bottom: 0.75em;
line-height: 1.2;
clear: both;
padding-left: 1.8em;
// the background box
&:before {
position: absolute;
content: " ";
border: 3px solid $darkgrey;
background: $darkgrey;
width: 16px;
height: 16px;
left: 0;
margin-top: -2px;
}
// the check/tick
&:after {
position: absolute;
content: " ";
width: 16px;
height: 16px;
left: 0;
margin-top: -2px;
}
}
// style :checked input span
&:checked + label span {
&:before {
content: "︎︎ ";
color: $blue;
background: $blue;
text-align: center;
border: 3px solid $blue;
}
&:after {
margin-top: 2px;
left: 8px;
width: 3px;
height: 8px;
transform: rotate(45deg);
border: solid $white;
border-width: 0 2px 2px 0;
}
}
}
}
JavaScript
// console log contents of checkbox (stored in array)
$(document).ready(function() {
var selectedOptions = [];
$(':checkbox[name="my_checkbox"]').change(function() {
selectedOptions = [];
$(':checkbox[name="my_checkbox"]').each(function(i, item) {
if($(item).is(':checked')) {
selectedOptions.push($(item).val());
}
});
console.log("selectedOptions:", selectedOptions);
});
});