CSS3 transition on click using pure CSS

user2498890 picture user2498890 · Feb 20, 2014 · Viewed 182.1k times · Source

I'm trying to get an image (a plus symbol) to rotate 45 degrees to create a cross symbol. I have so far managed to achieve this using the code below but its working on hover, I wanted to have it rotate on click.

Is there a simple way of doing so using CSS?

My code is:

CSS

img {
    display: block;
    margin: 20px;
}

.crossRotate {
    -webkit-transition-duration: 1s;
    -moz-transition-duration: 1s;
    -o-transition-duration: 1s;
     transition-duration: 1s;
    -webkit-transition-property: -webkit-transform;
    -moz-transition-property: -moz-transform;
    -o-transition-property: -o-transform;
     transition-property: transform;
}

.crossRotate:hover {
    -webkit-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
     transform: rotate(45deg);
}

HTML

<body>
   <img class="crossRotate" src="images/cross.png" alt="Cross Menu button" />
</body>

Here is the jsfiddle demo.

Answer

jeremyjjbrown picture jeremyjjbrown · Feb 20, 2014

If you want a css only solution you can use active

.crossRotate:active {
   transform: rotate(45deg);
   -webkit-transform: rotate(45deg);
   -ms-transform: rotate(45deg);
}

But the transformation will not persist when the activity moves. For that you need javascript (jquery click and css is the cleanest IMO).

$( ".crossRotate" ).click(function() {
    if (  $( this ).css( "transform" ) == 'none' ){
        $(this).css("transform","rotate(45deg)");
    } else {
        $(this).css("transform","" );
    }
});

Fiddle