
So we’ve all come across a design that requires some custom form elements including checkboxes. This simple CSS trick will allow you to fully customize your select boxes and you’ll be able to toggle them checked / un-checked without any additional javascript.
Ok, well in all fairness, we actually aren’t going to style the checkbox because that will be problematic, instead we’ll use a simple trick to allow you to use any element you want.
Ok, so lets start with a basic checkbox element. The important thing to notice is that the checkbox element is directly before the label for this trick.
// css // nothing yet // html
Alright, so now we’ll make some tweaks to create our own checkbox
// css // now our fake checkbox will be inside the label // we'll use the "+" css selector, this works because the checkbox is the element directly before the label input[type=checkbox] + label { display: block; position: relative; padding-left: 25px; } // we'll create the normal unselected checkbox input[type=checkbox] + label:before { content: ""; position: absolute; left: 0; top: 0; width: 20px; height: 20px; overflow: hidden; background-color: #b8b7b8; } // we'll create the selected version on our checkbox input[type=checkbox]:checked + label:before { color: #fff; content: "X"; background-color: green; } // html
Next lets hide the real checkbox, and do some more advanced styling just to show you how far we can go with this basic trick.
// css input[type=checkbox] { display: none; } input[type=checkbox] + label { display: block; position: relative; padding-left: 25px; } input[type=checkbox] + label span { position: absolute; top: 0; left: 0; width: 25px; height: 25px; background-color: #ccc; } input[type=checkbox]#testCheckbox3:checked + label span { background-color: blue; } input[type=checkbox]:checked + label span:after { content: ""; position: absolute; top: 50%; left: 50%; width: 20px; height: 20px; border-radius: 100%; background-color: green; -webkit-transform: translate(-50%,-50%); -ms-transform: translate(-50%,-50%); transform: translate(-50%,-50%); } // html
Thats it, happy styling!
Anthony Montalbano
If it's worth doing, it's worth doing right.
Published on: June 25, 2015
Last modified on: December 8, 2021