Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animated CSS transition on a tabbed element

Tags:

javascript

css

I have a jQuery tabs element with different tab heights. The outer div has dynamic height, but I want it to resize smoothly when the inner elements change tabs.

My current CSS is:

.parent{
  width:500px;
  background:green;
  padding:20px;
  transition:all 1s;

}

.tab1{
  width:300px;
  height:100px;
  background:red;
}

.tab2{
  width:300px;
  height:500px;
  background:blue;
  display:none;
}

.parent button{
  display:inline-block;
  vertical-align:middle;
}

This fiddle shows the behaviour: https://jsfiddle.net/mh5b91gx/

I've tried using min-height and max-height but couldn't get it done. Can you guys help me out?

like image 931
sigmaxf Avatar asked Oct 31 '22 04:10

sigmaxf


1 Answers

The closest thing I could come up with without changing your HTML is this: http://codepen.io/BenCodeZen/pen/rePLpP, but it's janky from a user's perspective and not something I would recommend.

$('#tab1').on('click', function(event) {
    $('.tab2').slideUp(400);
    $('.tab1').delay(400).slideDown();
    /* Act on the event */
});


$('#tab2').on('click', function(event) {
    $('.tab1').slideUp(400);
    $('.tab2').delay(400).slideDown(400);
    /* Act on the event */
});

The main issue with your code is that you're swapping out entire divs in the process. This means that you don't have a unified container to be smoothly transitioning heights. So the first step will definitely be changing your HTML structure to have a single content div which uses JavaScript or jQuery to change the content out.

Here's an example of what it might look like:

<div class='parent'>

  <button id="tab1">Tab1</button>
  <button id="tab2">Tab2</button>

  <div class="content">
    <div id="tab1-content" class="tab-content">...</div>
    <div id="tab2-content" class="tab-content">...</div>
  </div>

</div>

I would definitely recommend taking a look at the Organic Tabs article that @Asta, but let me know if you have any additional questions!

like image 61
bencodezen Avatar answered Nov 11 '22 13:11

bencodezen