While CSS alone cannot directly capture a click event, there are some clever workarounds available. One popular method involves using a checkbox:
div {
width: 120px;
height: 60px;
padding: 6px;
background-color: green;
color: white;
border: 5px solid blue;
}
input[type="checkbox"] {
display: none;
}
input[type="checkbox"] + label {
display: table;
margin: 25px;
}
input[type="checkbox"]:checked + label div {
background-color: orange;
color: black;
}
<input type="checkbox" id="cb1">
<label for="cb1">
<div>
Click Me - Div 1
</div>
</label>
<input type="checkbox" id="cb2">
<label for="cb2">
<div>
Click Me - Div 2
</div>
</label>
By enclosing the divs in labels associated with hidden checkboxes, any interaction within the label triggers a change in the checkbox state, causing CSS styling to be applied accordingly.
The selector
input[type="checkbox"]:checked + label div
targets checked checkboxes followed immediately by labels and their enclosed div elements. It is crucial that the label directly follows its corresponding checkbox in the HTML structure.
Feel free to customize this code to better fit your specific requirements.
UPDATE: In a previous iteration of this solution, the clickable area extended across the entire parent container due to the default behavior of labels. By utilizing display: table;
, this issue is resolved without compromising block-level functionality. Alternatively, you can opt for inline-block
to maintain divs on the same line as needed.