How To Style Checkboxes With CSS And a Bit of JQuery

Our goal today is to make a checkbox that has two states, checked and unchecked. Each state will be styled with CSS, we will choose when to apply one style or the other after we have checked with JQuery if the checkbox is checked or not.

Styling The Checkbox

The CSS am going to use for this tutorial is very simple. The first thing I want to do is hide the default look of the checkboxes.

input[type="checkbox"]{
display:none;
}

Next I want to have a class that I can apply to all the checkboxes regardless of their state. I want all the checkboxes to have white color font and corner radius and paddings of 10 pixels.

.checkbox{
padding:10px;
margin:5px;
cursor:pointer;
color:#ffffff;
-moz-border-radius: 10px; -webkit-border-radius: 10px;
}

I want to keep the styling simple for both checked and unchecked boxes, but you should be able to take it as far as you want easily. The unchecked boxes will be black and the checked ones red.

.checked{
background:#ff0000;
}
.unchecked{
background:#000000;
}

That is all we need for the CSS

The Checkbox Format

We can’t style checkboxes directly, that is why we set the display attribute to none, but we can wrap them around other elements and add labels to them.

In order for this script to work we will wrap our input checkbox tags around spans and we will add the styles we made above to the spans instead of adding them to the input tags.

Here is the code you will need for each checkbox you want to have in your form, you can have as many as you want.

<span class="checkbox">
<label>option one</label>
<input type="checkbox" name="option" />
</span>

The Magic Of JQuery

Since we hid our checkboxes we can’t click on them to check or unchecked them, BUT we can use JQuery to change their state when click we click on their parent span tag.

This following line will return the state of the box, true if it is checked and false if not.

$(this).children("input").attr("checked");

The "this" selector will refer to span tag inside the click function, you will see how this works in a moment.

If the box is checked we will remove the class "checked" and add the class "unchecked", we will do the opposite for unchecked boxes.

Here is the full JQuery code

$(document).ready(function() {

// assuming all checkboxes are unchecked at first
$("span[class='checkbox']").addClass("unchecked");
	
	$(".checkbox").click(function(){
	
		if($(this).children("input").attr("checked")){
			// uncheck
			$(this).children("input").attr({checked: ""});
			$(this).removeClass("checked");
			$(this).addClass("unchecked");
		}else{
			// check
			$(this).children("input").attr({checked: "checked"});
			$(this).removeClass("unchecked");
			$(this).addClass("checked");
		}
		
		alert($(this).children("input").attr("checked"));
	});
});

That’s it for this tutorial, enjoy!

blog comments powered by Disqus