I want the jQuery slideToggle effect but want to use CSS3 transitions in order to invoke the GPU on an iOS device so the transition is smoother.
You can achieve this by transitioning height
, padding
's and border-width
. Here is an example:
$('.run-css').click(function() {
$('.cont').toggleClass('toggled');
});
.cont {
width: 100px;
height: 100px;
border: 1px #CCC solid;
background-color: #EEE;
padding: 5px;
-webkit-transition: height .3s linear, padding-top .3s linear, padding-bottom .3s linear, border-top-width .3s linear, border-top-width .3s linear;
transition: height .3s linear, padding-top .3s linear, padding-bottom .3s linear, border-top-width .3s linear, border-top-width .3s linear;
}
.toggled {
overflow: hidden;
padding-top: 0;
padding-bottom: 0;
height: 0;
border-width: 0 1px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<button class="run-css">CSS slideToggle</button>
<div class="cont">Toggle this div</div>
-
11Yes it is. Pure CSS means that effect itself does not require JavaScript. I used JS for demo purposes to toggle class that triggers effect. – dfsq Feb 9 '15 at 4:04
Sorry but this is not supported by CSS3 unless you know the exact height. There is no way to animate between 0 and auto. If you do know the exact height, you can generate some transition codes here: http://css3generator.com/
-
That is the thing I am keep on looking for the solution without mentioning
height
– Mo. Nov 25 '15 at 9:59
True, you cannot animate between 0 and auto height, but you can actually toggle the max-height.
Toggle (via JS) between max-height:0
and max-height:1000px
and you'll get the achieved result, though it won't be quite as smooth as jQuery's slideToggle function.
Couple it with an opacity fade and it looks pretty good. I strongly suggest only using this technique on relatively short containers though, as the large ones can create a jerky animation.
-
1Interesting. I played with this and it's not the size of the container that makes it jerky... it's the difference between the
max-height
and the actual content height. Thus, you might as well need to know the content height, if you want to prevent a jerky experience (and if you know the content height, you can just transition overheight
). – bryanbraun Jun 17 '15 at 22:00
.container {
overflow-y: hidden;
max-height: 0;
transition: max-height 0.5s ease;
}
.container.open {
max-height: 1000px; /* approx */
}
I believe Animatable should do the trick. It's a CSS Transitions framework, and although I don't do iOS development, Lea Verou mentions that she test it on FF and Chrome for iOS.
There's other CSS animation libraries, like move.js that use CSS transitions and javascript.