I researched a lot, and I found this JSFiddle looks like what I need, but, when I click the button, the page background is changing. I want the button's color to be changed when clicked, instead.
div{
width: 100%;
height: 100%;
background: #5CB85C;
position: absolute;
top: 0;
left: 0;
z-index:1;
}
label.btn {
position: absolute;
top:10px;
left: 10px;
z-index:2;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
input[type="checkbox"]{
display: none;
}
input[type="checkbox"]:checked + div{
background: #5BC0DE;
}
label + input[type="checkbox"]:checked{
background: #000;
}
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet"/>
<label for="check" class="btn btn-default">Toggle background colour</label>
<input type="checkbox" id="check" />
<div></div>
This is fairly trivial. Simply move the "button" label
element to after the checkbox so that you can select it with the +
selector (this is called the adjacent sibling selector; there is no previous sibling selector, unfortunately), and change the CSS to match. JSFiddle
div{
width: 100%;
height: 100%;
background: #5CB85C;
position: absolute;
top: 0;
left: 0;
z-index:1;
}
.btn {
position: absolute;
top:10px;
left: 10px;
z-index:2;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
input[type="checkbox"]{
display: none;
}
input[type="checkbox"]:checked + .btn {
background: #5BC0DE;
}
/* label + input[type="checkbox"]:checked{
background: #000;
} */ /* I've commented this last selector out as it is unused per Harry's point in the comments */
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet"/>
<input type="checkbox" id="check" />
<label for="check" class="btn btn-default">Toggle background color</label>
<div></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With