Advanced Checkbox Hack

November 10th, 2012

Do you know the checkbox hack? Then you might want to know that the hack is not working on (older) iOS and (up to date) Android.

Before we jump into the solution, let's travel into the past.

Default Checkbox Hack (2011)

Chris Coyier showed us what we can do with the default checkbox hack:

HTML


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

CSS


input[type=checkbox] {
  position: absolute;
  top: -9999px;
  left: -9999px;
}

div {
  background: green;
}

input[type=checkbox]:checked ~ div {
  background: red;
}

css-tricks.com/the-checkbox-hack

Yeah, this is cool but there are two problems:

1. Doesn't work on Android <= 4.1.2

That's almost every Android device out there today (Nov. 2012). Shit.

Once upon a time there was a WebKit Adjacent/General Sibling & Pseudo Class Bug which doesn’t allowed you to use pseudo-classes combined with a adjacent (+) or general (~) sibling:

CSS


h1 ~ p { color: black; }
h1:hover ~ p { color: red; }

css-tricks.com/webkit-sibling-bug

Problem?

The default checkbox hack uses the pseudo-class :checked combined with the general sibling. And since on Android 4.1.2 the actual WebKit is 534.30 and it was fixed in WebKit 535.1, it's currently not working on the default Android browser.
jimbergman.net/webkit-version-in-android-version

Solution!

The best solution is to add a WebKit-only fake animation on the body element:

CSS


body { 
  -webkit-animation: bugfix infinite 1s; 
}
@-webkit-keyframes bugfix { 
  from {padding:0;} 
  to {padding:0;} 
}

stackoverflow.com/a/8320736/1012875

2. Doesn't work on iOS < 6.0

Oh yes, there are quite a few iOS devices where the default checkbox hack doesn't work.

Problem?

It’s not possible to click the label on iOS < 6.0 to toggle the input due to a bug.

Solution!

The best solution is to add an empty onclick to the label:

HTML


<label for="button" onclick></label>

stackoverflow.com/a/6472181/1012875

This leads us into only one direction... I present you the:

Advanced Checkbox Hack (2012)

We add the fake animation on the body for Android:

CSS


/* Fix Android */
body { 
  -webkit-animation: bugfix infinite 1s; 
}
@-webkit-keyframes bugfix { 
  from {padding:0;} 
  to {padding:0;} 
}

/* Hide checkbox */
input[type=checkbox] {
   position: absolute;
   top: -9999px;
   left: -9999px;
}

/* Like a link would behave */
label { 
  cursor: pointer;
  user-select: none;
}

We add the empty onclick on the label for iOS:

HTML


<!-- Fix iOS -->
<input type="checkbox" id="button" />
<label for="button" onclick></label>

In Action

Reduced Testcase

codepen.io/TimPietrusky/pen/fHmiI

Responsive Menu Concepts

Custom Dropdown

codepen.io/TimPietrusky/pen/gqlhA

Off Canvas

codepen.io/TimPietrusky/pen/CLIsl

Comments