Reputation: 142
I want to change the color of my checkbox (or label, or any other element) using only CSS based on the :checked
selector. The following is my HTML as I have it, and assume I cannot change it.
<div class="chk">
<label>
CheckMe
<input type="checkbox" id="myCheckBox">
</label>
</div>
I have tried using input[type="checkbox"] + label:before
in my CSS, but since the label
actually holds the checkbox rather than coming after it, this won't work.
I also have tried creating pseudo-elements after the label and checkbox, but have not been able to get that to work either.
Basically I am looking for this style of functionality: http://jsfiddle.net/zAFND but using only CSS and unfortunately I cannot change my HTML.
Upvotes: 0
Views: 797
Reputation: 660
Solution: You can try this Code...
label{
position: relative;
padding: 15px;
color: #000;
z-index: 1;
margin-top: 20px;
display: block;
}
input{
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
appearance:none;
-webkit-appearance:none;
-moz-appearance:none;
outline: none;
}
input:after{
content: "";
top: 0;
left: 0;
display: block;
width: 86px;
height: 42px;
position: absolute;
background-color: #ccc;
z-index: -1;
border-radius: 4px;
}
input:checked::after{
background-color: red;
}
<div class="chk">
<label>
CheckMe
<input type="checkbox" id="myCheckBox">
</label>
</div>
Upvotes: 2
Reputation: 1597
input[type="checkbox"]:checked {
border-radius: 2px;
appearance:none;
-webkit-appearance:none;
-moz-appearance:none;
width: 17px;
height: 17px;
cursor:pointer;
position: relative;
top: 5px;
background-color:#409fd6;
background:#409fd6 url("data:image/gif;base64,R0lGODlhCwAKAIABAP////3cnSH5BAEKAAEALAAAAAALAAoAAAIUjH+AC73WHIsw0UCjglraO20PNhYAOw==") 3px 3px no-repeat;
}
<div class="chk">
<label>
CheckMe
<input type="checkbox" id="myCheckBox">
</label>
</div>
Upvotes: 2
Reputation: 3994
You can use Jquery to achieve this.
$("input").click(function() {
$(this).parent().toggleClass('checked');
})
this will toggle class checked
to the parent label
when input changes
now you can style it as you want.
$("input").click(function() {
$(this).parent().toggleClass('checked');
})
label {
padding: 10px 20px;
border-radius: 3px;
}
.checked {
background-color: red;
color: white;
}
<div class="chk">
<label>
CheckMe
<input type="checkbox" id="myCheckBox" />
</label>
<script src="node_modules/jquery/dist/jquery.js"></script>
<script src="index.js"></script>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Upvotes: 2