css accordion using flexbox

Chris Purves

I'm trying to create an accordion using flexbox and transitions, adding and removing a collapse class with jQuery. The problem I'm having is if I set flex-basis as auto for the expanded divs, the animation doesn't work. See http://jsfiddle.net/vbLqg40h/ for an example. If I change the flex-basis from auto to 500px, the height of the flex container, the animation works ( http://jsfiddle.net/vbLqg40h/2/ )...I don't know why.

html

<div id="wrapper">
    <div id="box1" class="expand"></div>
    <div id="box2" class="expand collapse"></div>
    <div id="box3" class="expand collapse"></div>
</div>

css

#wrapper {
    height: 500px;
    display: flex;
    flex-direction: column;
}

.expand {
    flex: 1 1 auto;
    transition: all 2s;
}

.collapse {
    flex: 0 1 25px;
}

#box1 {
    background-color: yellow;
}

#box2 {
    background-color: green;
}

#box3 {
    background-color: blue;
}

javascript

$('.expand').click(function() {
  var expandId = $(this).attr('id');
  $('.expand').each(function() {
   var thisId = $(this).attr('id');
   if (expandId != thisId) {
     $('#' + thisId).addClass('collapse');
   } else {
     $('#' + thisId).removeClass('collapse');
   }
 });
});
DRD

To make the transition work, you will need to explicitly set the flex-basis. Here's a CSS-only solution of click-activated accordion: http://jsfiddle.net/zx854854/. If you want to persist the click-state, you can use radio input and label combinations.

HTML:

<div id="wrapper">
    <div tabindex = "1"></div>
    <div tabindex = "2"></div>
    <div tabindex = "3"></div>
</div>

CSS:

#wrapper {
    height: 300px;
    display: flex;
    flex-direction: column;
}

#wrapper > * {
    flex: 0 0 25px;
    outline: 0;
    transition: flex-basis 0.3s linear;
}

#wrapper > div:first-of-type {
    background-color: blue;
    order: 3;
}

#wrapper > div:first-of-type:not(:focus) + div:not(:focus) + div:not(:focus) {
    flex-basis: 250px;
}

#wrapper > div:nth-of-type(2) {
    background-color: green;
    order: 2;
}

#wrapper > div:nth-of-type(3) {
    background-color: yellow;
    order: 1;
}

#wrapper > div[tabindex]:focus {
    flex: 1 1 250px;
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

TOP Ranking

HotTag

Archive