{"id":15713,"date":"2011-12-21T12:36:30","date_gmt":"2011-12-21T19:36:30","guid":{"rendered":"http:\/\/css-tricks.com\/?p=15713"},"modified":"2020-01-24T17:04:06","modified_gmt":"2020-01-25T00:04:06","slug":"the-checkbox-hack","status":"publish","type":"post","link":"https:\/\/css-tricks.com\/the-checkbox-hack\/","title":{"rendered":"The “Checkbox Hack” (and things you can do with it)"},"content":{"rendered":"

The “Checkbox Hack” is where you use a connected <label><\/code> and <input type=\"checkbox\"><\/code> and usually some other element<\/em> you are trying to control, like this:<\/p>\n

<label for=\"toggle\">Do Something<\/label>\r\n<input type=\"checkbox\" id=\"toggle\">\r\n<div class=\"control-me\">Control me<\/div><\/code><\/pre>\n

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><\/code> still toggles its value on and off. Then you can use the adjacent sibling combinator to style the <div><\/code> differently based on the :checked<\/code> state of the input.<\/p>\n

.control-me {\r\n  \/* Default state *\/\r\n}\r\n#toggle:checked ~ .control-me {\r\n  \/* A toggled state! No JavaScript! *\/\r\n}<\/code><\/pre>\n

<\/p>\n

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.<\/p>\n

\n See the Pen
\n The Checkbox Hack<\/a> by Chris Coyier (
@chriscoyier<\/a>)
\n on
CodePen<\/a>.<\/span>\n<\/p>\n

Some of this stuff crosses the line of what you “should” do with CSS and introduces some questionable semantics. It’s still very fun to play with and cool that it’s possible, but in general, functional behavior should be controlled by JavaScript.<\/p>\n

Custom Designed Radio Buttons and Checkboxes<\/h3>\n

\n See the Pen
\n Custom checkboxes with CSS only<\/a> by Geoffrey Crofte (
@GeoffreyCrofte<\/a>)
\n on
CodePen<\/a>.<\/span>\n<\/p>\n

You can hide the default UI of a radio button or checkbox, and display a custom version right on top of it. <\/p>\n