CSS on a computer
|
September 6, 2018

Styling Checkbox – CSS Tips

Testable Network Layer in Swift  -  Part 1

How to style checkbox without using any CSS framework.

css styling for checkboxes

Let’s get to the point. Here is what a normal checkbox looks like:

css styling for checkboxes

(Default Checkbox)

How do we go about styling this?

HTML input-type checkboxes cannot be customized with any properties, so we have to get creative with how we customize the input element.

What? How?

Step 1: Hide the input element.

Step 2: Add an extra span element and apply your custom style by creating a class.

#1 — Hiding the Input

There are three ways to hide an HTML element.

  • Display: None
  • Visibility: Hidden
  • Opacity: 0

If we set display:none, then any event listeners (like click listeners) on that element will not work. We need functioning event listeners because the checkbox has to toggle its state from checked to unchecked when a user clicks on it.

Similarly, the problem with  visibility:hidden is that some of the events won’t work with this property set.

Damn!

If we set opacity:0, the element will be invisible but all the event listeners will still work; therefore, this is the property we will use to achieve our customization.

CSS:

With opacity:0 in place, this is how your checkbox will look:

#2 — Adding a Span Element

Why do we need a span element? Since we’re hiding the input checkbox and showing a custom-styled element that appears and behaves like a checkbox in its place, we use span as the placeholder element.  We use span  over block elements like div because it is an inline element that doesn’t take up the entire width.

Here is what our updated HTML would look like:

styling checkbox css

Let’s style the custom checkbox for unchecked state:

styling checkbox css

And again for checked state:

styling checkbox css

Now we can see our work in action:

css styling for checkbox

One last thing!

Let’s incorporate some fun by adding transition animation when the state changes from unchecked to checked and vice versa.

css styling for checkbox

With ripple effect:

css styling for checkbox

You can find entire source code for this demo below.


spreadsheets-are-bad-for-business-ebook

How Spreadsheets are Bad for Business eBook

Did you know that 88% of spreadsheets contain errors? While spreadsheets can be an effective tool for businesses, they propose serious risks. Our free eBook outlines the pros and cons of using spreadsheets to run your mission-critical operations. Download the ebook and start automating your unique workflows.
Pros of Spreadsheets
Cons of Spreadsheets (It's not what you think)
Next Step Solutions and How to Get Started
Bonus Case Study
Thank you! Enjoy our Healthcare Case Study!
Oops! Something went wrong while processing your request. Please try again or Contact Us for assistance.