CodeinWP CodeinWP

CSS3 Transitions Without Using :hover

Up to this point, the most common use for CSS3 Transitions has been in conjunction with the well-known CSS :hover pseudo-class.

Here’s a typical transition that changes link color on mouseover using pure CSS:

a, a:link, a:visited {
  color: lightblue;
  transition: color .4s linear;
}

a:hover {
  color: white;
}

This will animate the color property when you hover over a link on the page. Pretty simple, and you’ve probably seen or used something similar. But transitions are not just limited to use with :hover.

You can animate CSS properties, thus use CSS transitions without hover. This is done via transitions using some other CSS techniques, a number of which I’ve outlined below. I’ve also included a demo for each example.

Transitions Using :active

The :active pseudo-class matches any element that’s in the process of being activated. The primary way that an element is “activated” is by means of a mouse click, or mouse down.

Here’s some CSS and an accompanying demo that demonstrates using :active along with CSS3 transitions to mimic a mousedown event:

.box {
  width: 300px;
  height: 300px;
  background: #222;
  transition: width 2s ease, height 2s ease;
}

.box:active {
  width: 500px;
  height: 500px;
}

With this code, the box’s width and height properties are animated to become larger as you hold the mouse down on the element. Once you release, the box animates back to its original dimensions.

Here’s a demo:

Transitions Using :focus

You can use the :focus pseudo-class to do something similar. This time we’ll use a form, and we’ll animate the width of any form element that receives focus:

input, textarea {
  width: 280px;
  transition: width 1s ease;
}

input:focus, textarea:focus {
  width: 340px;
}

And here’s a live demo:

So that’s one way to do a CSS transitions without hover.

Transitions Using :checked

You can animate checkboxes and radio buttons when they become “checked” — although you’re limited with what you can do with those, since you can’t really change their native styling.

We’ll just do a simple width change, which will appear to indent any selected checkbox:

input[type="checkbox"]:checked {
  height: 20px;
  transition: width 1s ease;
}

input[type="checkbox"]:checked {
  width: 30px;
}

And here’s a simple demo:

Transitions Using :disabled

Keeping with the theme of web forms, this time we’ll combine CSS3 transitions with some jQuery to animate the background color of form elements when they become disabled via the disabled attribute:

input[type="text"], textarea {
  background: #e2e2e2;
  transition: background 1s ease;
}

input:disabled, textarea:disabled {
  background: #666666;
}

And the quick-and-dirty jQuery that adds/removes the disabled attribute is:

$(function() {
  $('input[type="radio"]').click(function() {
    if ($(':checked').val() === "other") {
      $('input[type="text"]').removeAttr("disabled");
    } else {
      $('input[type="text"]').attr("disabled", "disabled");
    }
  });
});

So when the last radio button is selected (the one with a value of “other”), the text box has its disabled attribute removed. If another option is selected, the disabled attribute is re-applied.

The :disabled pseudo-class is dependent on that attribute being present, so the animation will occur whenever that attribute is added or removed.

Here’s the demo:

Transitions Using Media Queries

This last one may be the least practical, because let’s face it, the only people that ever resize their window to see what happens are web developers.

Nonetheless, this is just another way to use CSS3 transitions. The new Modernizr design does this.

Here’s the code:

.box {
  width: 440px;
  height: 440px;
  background: #222;
  margin: 0 auto;
  transition: width 2s ease, height 2s ease;
}

@media only screen and (max-width : 960px) {
  .box {
    width: 300px;
    height: 300px;
  }
}

This example animates two different properties simultaneously, separating the two by a comma. The media query tells the box to shrink if the screen size goes below 961px.

Resize your window in the demo page to see it work:

Final Thoughts on Transitions Without Hover

The code examples that you can see in this post aren’t exactly the same as those used in the demo pages. I’ve made the code as brief as possible for the purpose of focusing only on the parts being discussed in this article.

This is pretty much all I could come up with for alternate ways to use CSS3 transitions. If you can think of another way to use transitions without hover, let me know in the comments.

65 Responses

  1. Very good article. However it does not solve a similar problem I’ve got. I want to trigger a transition on load.

    See this URL: http://stackoverflow.com/questions/6805482/css3-transition-animation-on-load

    • You can’t do that without JavaScript, and if you tried to use a delay or something, then it’s just going to confuse people, or else not even work correctly.

      Just use JavaScript. There’s no reason you shouldn’t be able to just use JavaScript for this; this is what JavaScript is for. CSS is not really made for that purpose.

      • Hamid says:

        Hi,I want the web page opens automatically. Of course, without mouse(active,hover,…).Please help me.

      • Bruce Bates says:

        you’re flat out wrong….they can be done without js

        http://codepen.io/chrissp26/full/szoyk

        • There’s nothing happening in that demo “on load”. You’re just doing an animation with CSS and it just so happens that it coincides with when the rest of the content is displayed. In a real website, there’s no guarantee that this will occur after the whole page has loaded. For example, what if there’s an image that takes 5s to load? Will the animation wait for that image? No, it will load as soon as the browser reads it, which is not really what was asked here, or in the Stack Overflow thread.

    • Ammon Casey says:

      you could do this by targeting a class that is added on load

      
      /* javascript */
      $(document).ready(function() {
          setTimeout(function(){
            $('html').addClass("loaded");
          }, delay);
      });
      
      
      /* css */
      .box {  
          width: 300px;  
          height: 300px;  
          background: #222;  
          -webkit-transition: width 2s ease, height 2s ease;  
          -moz-transition: width 2s ease, height 2s ease;  
          -o-transition: width 2s ease, height 2s ease;  
          -ms-transition: width 2s ease, height 2s ease;  
          transition: width 2s ease, height 2s ease;  
      }  
        
      .loaded .box {  
          width: 500px;  
          height: 500px;  
      }
      
      • Yeah, I was about to offer the same solution, but then realized he was asking to do this without JavaScript. But yes, this would definitely work.

        I don’t think you need the setTimeout function though. I think you can just use jQuery’s (document).ready. or else use the raw JavaScript onload event which actually waits a little bit longer than (document).ready, because (if I remember correctly), (document).ready doesn’t wait for images and external files to load, it only waits for the DOM to be built. (I might be oversimplifying this, just going from memory.)

        • Ammon Casey says:

          yeah, I just use the setTimeout so that I can control the delay. This lets me make sure assets are downloaded before I fade them in or something like that.

    • Jacob Dubail says:

      Use a body:hover .target_class to make the magic happen.

    • Divyam says:

      I guess you can do so with CSS3 Animations to do so. You can run the animation once to get the desired result. You can also set a delay if you want.

    • yashar azadvatan says:

      you can’t do it with “transition” but you can use “animation”!

      @keyframes example{
           from {width:10px;
            height:10px;
      }
           to{width:20px;
           height:20px;
      }
      }
      .myDiv{
      animation: example 2s;
      }
      
      It is the easy way,without javascript code!
      good luck
  2. David says:

    Your :focus, :checked and :disabled examples are simple but awesome. Will implement some of these tomorrow! :)

  3. Tom Durkin says:

    Cool ideas, I love transitions. Tend to use the ease in and out quite a bit

    Tom

  4. chistes says:

    Great tutorial guy. This will help me, thanks

  5. Jon Raasch says:

    You can also trigger transition just by adding a class (or setting the style attribute). You have the jQuery script for adding disabled, so just thought I’d mention there’s an easier way if you don’t want to use disabled (or want it on non-form elements)

  6. Great Post. Congratulations you have a really useful website :)

  7. Very nice article, I especially like the transition using media queries, it is very clean and elegant. Would you recommend it on a whole website that uses responsive layout and media queries to adapt to the screen size, or do you think it would be disturbing for the average user ? I know plenty of user who resize browser to fit there needs (if they’ve got a msn window open for example, etc). Of course they don’t resize as often as webdevelopers but it would be a nice eyecandy for those who do.
    I’m also wondering if those media query transition would work on ipad for instance when you change orientation? It could create a nice effect. I would do the test but I’ve no iPad.

  8. Dave Methvin says:

    Some great ideas here! On the checkbox one, the labels should really be in <label> tags so they become part of the click target. And the fact that the checkbox moves as part of the animation is probably not a good idea. Maybe something like this?

    http://jsfiddle.net/dmethvin/sRqG5/

    • Definitely, good points. I was a little worried about the checkbox thing being a little too weird, but mine was more of a proof-of-concept.

    • Ronny says:

      That’s exactly what I intended to suggest Dave :-) Maybe with the + instead of ~ combinator.

      Anyway, just note that IE7 has problems with <img> tags inside <label>s, apart from not understanding those combinators.

  9. Jasmine says:

    These transitions are simply great. Although I do not have great understanding on CSS3, but your demos and examples made them easier to understand.

  10. Nice examples. Especially for touch-based devices the named pseudo-classes are even more suitable, because of the lack of the hover functionality there.

  11. Daniel S says:

    Bookmarked. Great Article! Thanks for that.

  12. celsius says:

    awesome tips. thanks for sharing.

  13. Edwin Martin says:

    The :target pseudo-class should also trigger a transition. And should make some nice effects possible. (I haven’t tried this).

  14. Nice article. One year ago I build CSS3 Framework that uses Active, Hover and Target principles http://code.google.com/p/css3-action-framework/

  15. Jason says:

    Transitions does work with some of the html5 forms validation psuedo-classes.

    You can have a transition from :invalid to :valid

  16. Transition with media queries works on smartphone Android (dolphin) after loading page, not after refresh, but it’s really cool

  17. Aniket Pant says:

    Brilliant article :)

    Totally love it.

    I didn’t know most of these tricks :D

  18. The problem with using :active to mimic a mousedown state is that you can click on a link, hold, then move your mouse off and the anchor will remain stuck in that state. Use with care!

  19. Alessandro says:

    Beautiful article! Really Interesting! Thank you so much!

  20. Alex says:

    Nice article. Some of these transitions are entirely new to me.

  21. Hallo,
    wow thats realy cool. the Transitions Using Media Queries is the best. Thank you so much. Greetings from Germany.

  22. Lindsay says:

    To write CSS manually is not tough, if you know the properties you can easily write CSS. But what if you are too lazy to write your own code then there are lots of ways that may help you do it. Writing CSS3 codes are actually for patient people most especially but if you are done with doing it manually Im pretty sure you will be more than glad of seeing the results.

  23. Mark says:

    Great stuff. It’s nice to see some one do something different with CSS animations. I love the subtle movement too. Thanks.

  24. Ana says:

    Maybe this should have been pretty obvious from the beginning, but here is something I noticed while playing with transitions + media queries and going from fixed to fluid (or from fluid to fixed) width: transition is from the fixed width to 0 (or from 0 to the fixed width) unless a min-width is specified.

  25. anonymous says:

    I used your trick on one of my client’s website. Looks perfect and I was told that visitors also like it very much, see yourself on this page -> http://pevex.com.cy/cyprus_company_formation.html and try to hover on the table which describes advantages…

  26. Shaf Syed says:

    The transitions using :active seems like what I am looking for exactly. BUT with the divs floated side by side. Can you please email me the code for the exact solution if you have time? I would really appreciate it. Let me try to explain:

    Basically I am looking for the onMouseOut for the left and right divs to go back to its original width such as 50%. So the onMouseOver on either the left or right div will expand it to 80% while the opposite side decreasing to 20% This would work the same if for the other side too. When the user mouses over the right side which is currently at 20% the right div would expand to 800% and the opposite div will be at 20%. This transition happens simultaneously and is smooth. AND I am only coding for IE 9+, Safari, Chrome, Firefox.

  27. Tekinsol says:

    The transition effects in css3 are really great at least they eliminate the use of those complicated jquery plug ins. Great article… thanks.

  28. Dazines says:

    Finally something good and descriptive. I’m playing with CSS about half year and believe it or not, it’s the first time I see that :checked selector. Good article, great blog, already bookmarked :)

  29. Analí says:

    Hi!
    Thank you, your post has very interesting examples.
    I appeal to your expertise, because I wonder: Do you know how to do the effect done in the main text in this website? http://www.buildacity.org/
    In every movement of the mouse, the font color changes, looks really cool.

  30. Vinay says:

    Superb and different article compared to rest of the css3 transitions mate!!

  31. Chris McLaughlin says:

    Hi Louis,

    Great examples. I did try the “active” example on iPad running iOS7 and iPhone 5 running iOS6 and it did not work. Perhaps you have discovered a solution since the article was published. If so, I would be very happy to learn it.

    Best,

    C.S.

  32. Darius says:

    I found the tutorial useful and used some of these transitions on my own websites. Thanks a lot.

  33. Kwiatek says:

    Hi,
    It could be with :target function like this:

    
    <html>
    <head>
    <style>
    #container {
    	position: absolute;
    	left: 20px;
    	top: 20px;
    	width: 920px;
    	height: 600px;
    	background: #CCCCCC;
    	color: #ffffff;
    	transition: 2s;
    	text-align: center;
    	display: block;
    }
    #box_1 {
    	position: absolute;
    	left: 20px;
    	top: 20px;
    	width: 100px;
    	height: 100px;
    	background: blue;
    	color: #ffffff;
    	transition: 2s;
    	text-align: center;
    	display: block;
    }
    #box_1 a {
    	position: absolute;
    	width: 100px;
    	height: 100px;
    	background: blue;
    	color: #ffffff;
    	transition: 2s;
    	text-align: center;
    	display: block;
    }
    #box_1 a:hover {
    	position: absolute;
    	width: 100px;
    	height: 100px;
    	background: blue;
    	color: #ffffff;
    	transition: 2s;
    	text-align: center;
    	display: block;
    }
    #box_2 {
    	position: absolute;
    	right: 20px;
    	top: 20px;
    	width: 100px;
    	height: 100px;
    	background: yellow;
    	color: #ffffff;
    	transition: 2s;
    	text-align: center;
    	display: block;
    }
    #box_2 a {
    	position: absolute;
    	width: 100px;
    	height: 100px;
    	background: yellow;
    	color: #ffffff;
    	transition: 2s;
    	text-align: center;
    	display: block;
    }
    #box_2 a:hover {
    	position: absolute;
    	width: 100px;
    	height: 100px;
    	background: yellow;
    	color: #ffffff;
    	transition: 2s;
    	text-align: center;
    	display: block;
    }  
    #box {
    	position: absolute;
    	left: 20px;
    	top: 40px;
    	width: 300px;
    	height: 300px;
    	background: black;
    	color: #ffffff;
    	transition: 2s;
    	text-align: center;
    	display: block;
    }  
      
    #box:target {
    	position: absolute;
    	left: 400px;
    	top: 40px;
    	width: 500px;
    	height: 500px;
    	color: #ffffff;
    	background: red;
    	text-align: center;
    	display: block;
    }
    </style>
    </head>
    <body>
    <div id="container">
    <div id="box">
    	<div id="box_1"><a href="#">back</a></div>
    	<div id="box_2"><a href="#box">forward</a></div>
    </div>
    <a href="#">back</a> <a href="#box">forward</a>
    </div>
    </body>
    </html>
    
  34. Ray John says:

    These transitions are very dynamic and beautiful! I especially like the :active one, thanks for this post.

  35. Alex Banner says:

    Hey there. Thank you for this amazing tutorial. I tried some of the things that you explained and it helped me alot, especially with the :active command.

  36. Dinco says:

    Wow! Nice work man.I adore animations and transitions. I will try some of these in my future projects.

  37. ayushi says:

    very nice article but i want to know how to increase height of div from 0px to 50px on page load automatically in transitio property.

    • Well, you can’t do it on page load. You can use an animation/transition delay to mimic that, but you can’t test page load with CSS.

      Instead, do something like with JavaScript:

      window.onload = function () {
        element.classList.add('transition-stuff');
      };
      

      This will add the class “transition-stuff”, on which you have the transitions defined, so they will only trigger on page load. Or use addEventListener to do the same thing, which might be better.

  38. William says:

    It’s a Brilliant post. I really like your article. This article was helpful. Thanks for sharing your concept.

  39. Elsa Smith says:

    Great job! I’m really impressed with the animations and transitions you’ve done. I can’t wait to incorporate some of these into my next click project.

Leave a Reply

Comment Rules: Please use a real name or alias. Keywords are not allowed in the "name" field and deep URLs are not allowed in the "Website" field. If you use keywords or deep URLs, your comment or URL will be removed. No foul language, please. Thank you for cooperating.

Markdown in use! Use `backticks` for inline code snippets and triple backticks at start and end for code blocks. You can also indent a code block four spaces. And no need to escape HTML, just type it correctly but make sure it's inside code delimeters (backticks or triple backticks).