user479947
user479947

Reputation:

Adding CSS transition or Javascript animation to auto sized flex box layouts

I'm experimenting with a design pattern using .expands to toggle .hidden child classes for .expanded auto-sized flex box elements.

Something like:

const expandClick = e => {
  e.currentTarget.querySelectorAll('.expanded').forEach(child => {
    child.classList.toggle('hidden')
  })
}

document.querySelectorAll('.expands').forEach(expandable => {
  expandable.addEventListener('click', expandClick)
})

https://jsfiddle.net/vpc8khq8/

When my inner content loses the display: none attribute, I would like the height to ease out with a slight bounce, but I'm not quite sure how to pull that off with a vanilla CSS transition or a pinch of JS.

I came across this post: How can I transition height: 0; to height: auto; using CSS?

But many of the answers seem more like hacks with odd side effects and excess js / css than simple, lightweight solutions.

This does the trick with jQuery: https://jsfiddle.net/cm7a9jr7/

const expandClick = e => {
  $(e.currentTarget).children('.expanded').each(function() {
    $(this).slideToggle('slow', 'swing', function() {
      $(this).toggleClass('hidden')
    })
  })
}

$(() => $('.expands').on('click', expandClick))

But, I'd like to use something leaner. Are the any recommended libraries or simple ways to pull this off in CSS?

Upvotes: 1

Views: 194

Answers (1)

Pixelomo
Pixelomo

Reputation: 6737

I've updated your fiddle https://jsfiddle.net/vpc8khq8/2/

Instead of using display none you can get a transition effect by setting max-height to 0 on the hidden section then change the max-height to a fixed height (greater than the section will ever be) to reveal. This also requires you to set overflow hidden on the parent element:

.expands{overflow: hidden;}

section.hidden { 
 max-height: 0;  
 background: red;
}

section{
  transition: 1s cubic-bezier(0.35, 1.17, 0.39, -0.61); 
  max-height: 400px;  
  background: blue;
}

I've created a semi-decent cubic-bezier to get the bounce effect, though with a bit of refinement you could probably get something better.

If you open chrome devtools and click on the transition icon you can select from a number of presets and also create your own by moving the curve points around. Devtools will show you a preview of the transition and you can test it out without reloading. Then just copy that cubic-bezier code back to your CSS.

enter image description here

To take it a step further you could achieve all of this without any JS, using hidden checkboxes and some CSS trickery along the lines of this example: https://codepen.io/mrosati84/pen/AgDry

Upvotes: 0

Related Questions