CSS Checkbox Hack

february 10, 2024 - css

In the case of the "checkbox hack," we take advantage of this selector to create dynamic effects based on the state of a checkbox.

By using the :checked pseudo-class along with the adjacent sibling selector (+), we can target and style elements that are adjacent to a checked checkbox.

This allows us to create various effects like changing the appearance, visibility, or behavior of elements in response to the checkbox state.

image domain

CSS checkbox hack examples

 

I created three "checkbox hacks examples" to let you see how it works.

See the Pen checkbox-hacks by marcello (@tofjadesign) on CodePen.

 

image domain

checkbox 1 explained

 

When you check the checkbox, the label will change its background color to green and text color to white, creating the CSS stunt effect.

/*checkbox hack 1*/

#checkbox1:checked + label {
background-color: red;
color: white;
}

image fireworks

checkbox 2 explained

 

In this second example, when you check the checkbox, the adjacent .box element will change its background color to green and rotate 45 degrees using the CSS transform property.

/*checkbox hack 2*/

 

#checkbox2 {
width: 25px;
height: 25px;
}

 

#checkbox2 :checked + .box {
background-color: green;
transform: rotate(45deg);
}

.box {
margin-top:30px;
width: 50px;
height: 50px;
background-color: blue;
transition: all 0.3s ease;
}

css

checkbox 3 explained

 

In this third example, when you check the checkbox, the adjacent .container element will disappear by setting its display property to none.

/*checkbox hack 3*/

 

#checkbox3 {
width: 25px;
height: 25px;
}

 

#checkbox3 :checked + .container {
display: none;
}

.container {
margin-top:30px;
width: 50px;
height: 50px;
background-color: green;
transition: all 0.3s ease;
}

#checkbox3 :checked ~ .show-text {
display: block;
}

.show-text
display: none; {
font-size: 24px;
color: blue;
}

image domain