Style Checkboxes – using CSS custom properties

The “input” elements of type checkbox are rendered by default as square boxes that are checked (ticked) when activated, like you might see in an official government paper form. They allow you to select single values for submission in a form (or not).

First, structure the checkboxes on following way

  
<input type="checkbox" id="checkbox-a" name="checkbox" />
<label for="checkbox-a">...</label>

 

The “id attribute” on the “input”, allows us to connect it to the appropriate “label” using the for “attribute”. You’ll notice the 2 values are same.

Now user can actually click on the label, and the checkbox will be selected. It increases our target area. Plus,you can style an element completely differently depending on the state of that checkbox.

  
input[type='checkbox'] {
    opacity: 0;
}

input[type='checkbox']:checked +label {
    ...
	....
	..
}

 

This is the way custom CSS is working.

Note: Try to use ‘opacity’ or ‘positioning’ properties to hide the input element because ‘display: none’ ignored by screen readers and keyboard tabbing.

The “+” mark is indicate the right next label of checkbox, for style the label.
Note: it’s the second label, you’re not styling the first label.

  
input[type='checkbox'] +label {
	....
}

 

We can use “:checked” pseudo-class to target checked checkbox.

  
input[type='checkbox']:checked +label {
    ...
	....
	..
}

 

Now, everything works like you would expect a checkbox to work.

Here’s our final output:

View live demo : Click here

Another working demo on : Code Pen

Download source code : Git Hub

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *