Created
December 21, 2011 16:00
-
-
Save chriscoyier/1506530 to your computer and use it in GitHub Desktop.
Checkbox Hack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Checkbox Hack */ | |
input[type=checkbox] { | |
position: absolute; | |
top: -9999px; | |
left: -9999px; | |
} | |
label { | |
-webkit-appearance: push-button; | |
-moz-appearance: button; | |
display: inline-block; | |
margin: 60px 0 10px 0; | |
cursor: pointer; | |
} | |
/* 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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<label for="toggle-1">I'm a toggle</label> | |
<input type="checkbox" id="toggle-1"> | |
<div>I'm controlled by toggle. No JavaScript!</div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{"view":"split-vertical","prefixfree":"1","page":"css"} |
Hi there,
Was just having a look at this.
Is there a way to have any of the buttons toggle all of the divs?
So just like one button toggles the two divs when you're using ~, is there a way to select by button class so that any button controls all divs? Is something like that possible??
Thanks,
Enrik
Hi @enrikpavdeja!
If you add a new label & input:
<label for="toggle-all">I toggle all</label>
<input type="checkbox" id="toggle-all">
then modify the toggled state definition:
/* Toggled State */
input[type=checkbox]:checked + div, #toggle-all:checked ~ div {
background: red;
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There is a problem with the css. If you have more than one div, the first checkbox will toggle all subsequent divs. So change the css to use
+
instead of~
Updated demo