Reputation: 33
I've been struggling with CSS height transitions today. I'd like to use it in several places in my little project, but I can't get right...
Here is a little widget replicating the solution I'm working on right now: JSfiddle
When clicking the "this is a button", I would like the height transition take place. Before clicking the login form should be hidden. When I set the height value of the form to 0, it behaves really strange. I've looked through some tutorials, which suggest using max-height
, but I still get awkward results.
When the "this is a button" has been clicked and the full height of the form has been achieved, it should transition its height to 0 or disappear, when clicked the upper button again.
I think transitioning every element inside the form is really a stupid/wrong approach - that's the last thing I can come up with, lol...
I'm out of ideas and couldn't think where to look for possible solution...
Upvotes: 0
Views: 213
Reputation: 16733
To start off with, you need to set your form's height to 0, and set it's overflow to hidden so that its contents won't bleed out:
form{
height:0;
overflow:hidden;
transition: height 0.3s;
}
Now that the transition is setup, you need to define a class that, when applied to the form, will trigger that transition:
form.expand{
height:100px;
}
Unfortunately, you need to define a height in units - using auto won't work.
Now, you need to add some javascript. No way getting around it, stylesheets don't know anything about button clicks:
var btn = document.querySelector('.btn');
btn.addEventListener('click', function(){
var form = document.querySelector('#login-form');
form.className = form.className + ' ' + 'expand';
});
This script listens for clicks on the button, and adds the expand
class to our form dynamically, which triggers the transition.
If you don't like having to code a height measurement for this, opacity
is a popular alternative.
Upvotes: 1