Simple slide in content with pure CSS3

The problem

We had some great new characters made for our game screen. It seemed a lot more fun to bring them to life by having them pop into the page and then slide back out. We decided to do this with CSS only.

Our new character in the game

We tried a few different ways of making this work cleanly and degrade to a simple show and hide in old browsers such as IE6 and 7. A couple of problems we faced at first were divs sliding off the page causing scrollbars to appear in old browsers, and using CSS animations when in the end we found the transitions to be simpler and more effective for this task.

One of the keys to making this work was to avoid display: none to show and hide anything. Transitions don’t work for elements that are display: none at the start, so it’ll requires a lot more code and extra elements. In the end by setting the height at 0px it appears to be ‘hidden’ but is actually still on the page, the transform will then work on this value.

This is a just simple post and some code for you to play with as we found it to be really useful.

The code

The wrapper selector is the overall area in which our content will live in. Setting both the open and closed state at 500px wide means that it will slide in neatly from the bottom. If you set the width to anything lower than 500px on the initial wrapper it will ‘grow’ out from a point in both directions, which is also a nice effect if you prefer that.

You can also make the initial height 500px and width 0, this will cause the element to slide in from the left side.

This degrades nicely into IE6 and 7 as a simple show and hide, it also has a relatively small amount of code. Check out the demo to see it in action and grab the code.

Don’t forget you can also adjust the time of the transition to make it faster or slower, I decided to go with .5 seconds. You can also play around with the timing function to ease in and out, or have simple linear transition. There’s a fun little bezier creator you can use for this, and for a basic insight into CSS3 transitions A List Apart has a nice article.

.wrapper {
  display: block;
  position: absolute;
  width: 500px;
  height: 0;
  bottom: 0;
  left: 0;
  overflow: hidden;
  -webkit-transition: all 0.5s;
  -moz-transition: all 0.5s;
}

.wrapper.shown {
  width: 500px;
  height: 500px;
}

.wrapper.shown .content {
  -webkit-transform: translate(0px, 0px);
  -moz-transform: translate(0px, 0px);
}

.content {
  width: 480px;
  height: 480px;
  padding: 10px;
  position: absolute;
  bottom: 0;
  background: red;
  color: #FFF;
  -webkit-transform: translate(0px, 500px);
  -webkit-transition: all 0.5s;
  -moz-transform: translate(0px, 500px);
  -moz-transition: all 0.5s;
}

I’m sure there are many ways to reproduce this same task - so let us know if this is was helpful to you, or if you have any better techniques!

Posted on 09 September 2011 by Tim P & Tim R @timparker.
blog comments powered by Disqus