CSS-based click functions without jQuery

I stumbled upon this technique quite a while ago when toying about with the images in my portfolio, so I thought I’d document it here: how to essentially create click functions without using jQuery.

I don’t like to rely on jQuery too much – when CSS3 arrived a whole world of new options came with it. Admittedly, they’ll only work in new browsers (anyone out there still using Internet Explorer 8 – or older – please for the love of all things holy would you upgrade your browser!)

Anyway, onto the click function.

This is based primarily around the sibling selector (+ or ~) in css. The idea is to have a transparent checkbox on the page on top of your event trigger which, when checked, will alter the styling of another element.

In my example, the idea is to have an image, inside of a main div, that fills the space. When clicking the image, it shrinks to only fill half the width of the container.

The markup is nice and simple:

<div>
    <input type="checkbox" />
    <img src="your url here" alt="can be any other element" />
</div>

And the styling:

div {
    position: relative; 
    text-align: center;
}
div input { 
    opacity: 0;
    filter: alpha(opacity=0);
    width: 100%;
    height: 100%;
    top: 0; 
    left: 0; 
    z-index:1;
    position: absolute;
    cursor: pointer;
}
div img { 
    width: 100%;
    height: auto;
    -webkit-transition: all 0.3s;
    -moz-transition: all 0.3s;
    -o-transition: all 0.3s;
    transition: all 0.3s;
}
div input:checked + img {
    width: 50%;
}

And that’s it - the checkbox will be invisible, on top of the image. So when the image is clicked, it will animate to only half the width of the container. And when clicked again, it will animate back.

example image


Posted: January 6th, 2014
Categories: code