Stuff you can do with the “Checkbox Hack”

Published by Chris Coyier

The "Checkbox Hack" is where you use a connected label and checkbox input and usually some other element you are trying to control, like this:

<label for="toggle-1">Do Something</label>
<input type="checkbox" id="toggle-1">
<div>Control me</div>

Then with CSS, you hide the checkbox entirely. Probably by kicking it off the page with absolute positioning or setting its opacity to zero. But just because the checkbox is hidden, clicking the <label> still toggles its value on and off. Then you can use the adjacent sibling combinator to style the <div> differently based on the :checked state of the input.

input[type=checkbox] {
   position: absolute;
   top: -9999px;
   left: -9999px;
   /* For mobile, it's typically better to position checkbox on top of clickable
      area and turn opacity to 0 instead. */
}

/* Default State */
div {
   background: green;
   width: 400px;
   height: 100px;
   line-height: 100px;
   color: white;
   text-align: center;
}

/* Toggled State */
input[type=checkbox]:checked ~ div {
   background: red;
}

View Demo

So you can style an element completely differently depending on the state of that checkbox, which you don't even see. Pretty neat. Let's look at a bunch of things the "Checkbox Hack" can do.

Disclaimer: Some of this stuff crosses the line of what you "should" do with CSS and introduces some bad semantics. It's still wicked fun to play with and cool that it's possible, but in general functional behavior should be controlled by JavaScript.

Custom Designed Radio Buttons and Checkboxes

Hide the default UI of a radio button or checkbox, and display a custom version right on top of it. Probably not generally good practice, as users are familiar with default form elements and how they work. But can be good for enforcing cross browser consistency or in situations where the UI is so obvious anyway it's just for fun.

File system like "tree menu"

Demo by Ryan Seddon

Tabbed Areas

The "tabs" design pattern is just toggling on and off of areas, perfect for the checkbox hack. But instead of checkboxes, in which any checkbox can be on or off independently of one another, these tabs use radio buttons in which only one per group can be on at a time (like how only one tab can be active at a time).

Functional CSS tabs revisited

Dropdown Menus

Original by paullferguson and then Forked for betterness by me

Push Toggles

From What's My MPG?

Options from Dabblet

FAQ Answer Revealing


View Demo

More

A couple demos by Gene Locklin: