CSS -> How to Make your own input checkbox button

The Backstory

I was working on a project where the last developer made a custom input radio button by using a png as the background and shifting the positions when clicked. Unfortunately, I never got to meet the developer IRL because if I did I would have said 2009 called and it wants its code back. Good ridden! It’s a total kick in the face to HTML5 and CSS3 and all the progress they have made, so we don’t have to do such ridiculous hacks any longer.

The How-To

First thing you are going to want to do is make an <input> tag along with a <label> tag, Inside your <input> tag make sure to include a unique id for that element. Then, create a <label> tag with an attribute “for”. The for attribute is used in HTML 5 to allow the browser to use the <label> tag to control whatever id the tag is set to. So in this example, the <label> tag would be connected to our <input> tag. Example:

<div class="input-container">
<div>
<input type="checkbox" id="checkbox_id_goes_here">
<label for="checkbox_id_goes_here"></label>
</div>
</div>

I wrapped the two HTML elements in a container (a parent element that in this case is a div). After building your HTML code, move on over to your CSS you are going to want to hide the <input> element because you are going to use the <label> instead. In your CSS, simply add a class with the following properties

.input-container > div > input[type=checkbox] {
position : absolute;
visibility : hidden;
}

After you have hidden you checkbox, you will want to configure the look of the label to display as a checkbox. In order to do that you will want to use this code:

.input-container > div > input[type=checkbox] {
position : absolute;
visibility : hidden;
}
.input-container > div > label {
width : 24px;
height : 24px;
background : #ffffff;
}
.input-container > div > input[type=checkbox]:checked ~ label:after {
content : "\2713";
color : #0094fe;
font-size : 22px;
}

So essentially what this code is saying is:

  1. hide the input box ( .input-container > div > input[type=checkbox])
  2. make the label with a background of white and a 24px square (.input-container > div > label )
  3. If the label is clicked, it will set the attribute for the input to “checked”, if that input has a checked attribute returning true when the browser checks, look for its siblings ( that what the ~ does ) inside the container and insert some additional code into the HTML view that everyone can see. (.input-container > div > input[type=checkbox]:checked ~ label:after)

The Result

I’ve tried this on CodePen and JSFiddle and it doesn’t work. I have no idea why, but it works when you use it in Google Chrome, so I will update this post with more info on why it doesn’t work in CodePen or JSFiddle.

For now, Happy Coding.