css-checkbox-button-hack
CSS Web Development

The CSS Checkbox Button HACK!

So let’s look at this button. It has the glass cover that we need to click it to open and show the actual button inside. And if you change your mind, you can click it again to close it. This means we have to keep track of the close and open state.

css-checkbox-button-2

In previous tutorial, I used a JavaScript to add and remove the class. This works fine. But if you are looking for a pure CSS approach, then we need to find another way. In this tutorial, we’ll show you the CSS checkbox hack technique and turn it into button that we can track the state (super useful for creating toggle button) Ready? Let’s check it out!

The Concept

Here is the basic checkbox.

css-checkbox-button-1

You might know it already that it’s not necessary to click at the box in order to mark it. You can also click the label and it will work just the same. So the trick is if we hide the box. Then add the CSS to style the label, it will look and work the same as button. Only this time we’ll be able to keep track the click state from the checkbox!!

Checkbox Toggle Button

So let’s start with adding hidden attribute to the input tag. This will hide the box completely and leave us only the label.

<input type="checkbox" id="checkbox1">
<label for="checkbox1">Click Me!</label>

Then I’ll set the label size, background color and flex layout to center the text. Also change the cursor to pointer.

label {
  width: 200px;
  height: 100px;
  background: #c5101f;
  color:white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 30px;
  cursor: pointer;
}

css-checkbox-button-3

Now we can keep track button state by using check status of the input and change the background color to green!

input:checked ~ label {
  background: #09ff00;
}

Try it on Codepen!

Let’s Test It!

Now you got basic. Let’s apply it to the button from previous tutorial.

chernobyl-az-5-button-css-6

First let’s add a hidden checkbox next to cover-wrap. Then change the cover-wrap div to label.

<input type="checkbox" id="checkbox1" hidden>
<label class="cover-wrap" for="checkbox1">

Also remove all the JavaScript since we don’t it anymore!

Finally, update the CSS rule. Instead of using active class to track the close and open state, we’ll use the checkbox status.

#checkbox1:checked ~ .cover-wrap {
  ...
}

So now the button cover works the same as before except it’s pure CSS now! (Download the project code here)

And that’s all for this tutorial. Hope you guy enjoy!

Written By

Leave a Reply

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

error: