Latest News & Blog

CSS Tricks: Using images as checkboxes in your html forms

Friday 7 December, 2018

Blog CSS Tricks

One element that is particularly complicated to style using simple css and that is very common on a website design is an input box, specially those of type checkbox. You will notice with time that apart from the size and border color, it is very difficult to achieve the desired results when you want to modify it and use something different than a simple square. But the following css pattern is here to save the day!

Let's say for example that you have 2 images that will need to work as an input checkbox, one for the unchecked version and one for the checked version. It can be anything, maybe a box with some text that when clicked changes to something else and it needs to "check" something on a form and you don't want to use those squares. The solution is to use the :checked css selector.

For this example we will use the following html structure:


Some text

What we want to achieve is when you click the label (which will be an image or an icon) the input field will change to "checked" and the label image will change to something different.

First we hide the input field with a display:none and then we style the label to have a background image. We are using the "+" sign to select the label that comes imediatly after the input box.

.my-custom-input-label-box input[type="checkbox"] {
	display:none;
}

.my-custom-input-label-box input + label {
	display: inline-block;	
	width: 60px;
	height: 30px;
	cursor: pointer;	
	background-image: url(/images/service/checkbox-unchecked.png);
}

Then we make the label change it's background image when clicked by making it listen to the :checked selector of the input. This css basically means "when my input box is checked, change the background image of the label that comes next in the html structure"

.my-custom-input-label-box input[type="checkbox"]:checked + label {
	background-image: url(/images/service/checkbox-checked.png)
}

And that is it! Something very simple and yet very powerful. You can use your imagination and use this pattern for other things. For example, you can have an input + div html structure, make the input transparent, absolute position it on top of the div and make the input change the div styles when the hidden input is checked. the pattern is the same.

Hopefully this article can help you with your website designs. Stay tuned for more CSS tricks.

Written By...

Leenix