CSS Click Event : Using CSS for Click Events

CSS doesn’t provide any official way to handle a click event in CSS. But there are some very interesting tricks that we can use to “detect” a click using CSS only, without a single line of JavaScript, and this is what we are going to talk about today.
How ot Works ?
The HTML
1
2
<input type="checkbox">
<p class="to-be-changed">I'm going to be red! It's gonna be legen... Wait for it...</p>
The CSS
1
2
3
4
5
6
7
.to-be-changed {
    color: black;
}
 
input[type=checkbox]:checked ~ .to-be-changed {
    color: red;
}
As you can see, it relies on the :checked pseudo-class and on the general sibling selector ~. Please note that it also works like a charm with the adjacent sibling selector +. Basically, it says “if the checkbox is checked, then the following elements with the .to-be-changed class will be red”.
Okay, a checkbox isn’t very sexy, but you can totally make something nicer by hiding the checkbox and binding a label to it. Something like this maybe:
1
2
3
<input type="checkbox" id="toggle">
<label for="toggle">Click me!</label>
<p class="to-be-changed">I'm going to be red! It's gonna be legen... Wait for it...</p>
So we hide the checkbox and use the label to trigger the click event.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
input[type=checkbox] {
    position: absolute;
    top: -9999px;
    left: -9999px;
}
 
label {
    display: block;
    background: #08C;
    padding: 5px;
    border: 1px solid rgba(0,0,0,.1);
    border-radius: 2px;
    color: white;
    font-weight: bold;
}
 
input[type=checkbox]:checked ~ .to-be-changed {
    color: red;
}
This way, you have some kind of button triggering the color change on the paragraph. Isn’t that cool? Re-clicking on the button is switching the color back to black of course.
(Note that there are different possibilities for hiding the checkbox, the most obvious of all being display:none.)
Changing Color or Click Event with CSS

Comments

Popular posts from this blog