yaserso
yaserso

Reputation: 2868

Max-height transition from 0 to auto or none?

I have an element with a max-height of 0. I want to transition it to no max-height auto or none; whatever makes it expand based on the number of elements present. I don't want to use JS nor flex, yet.

Here's the jsfiddle: https://jsfiddle.net/m9pd8bjh/19/

HTML:

<nav>
  <input type="checkbox" id="menu-main-checkbox" hidden>
  <label class="toggler" for="menu-main-checkbox">Menu</label>
  <div class="hide toggleable">
    <ul>
      <li>Home</li>
      <li>Sample Page</li>
    </ul>
  </div>
</nav>

CSS:

.hide {
  visibility: hidden;
  overflow: hidden;
  max-height: 0;
}

input[type=checkbox]:checked~.toggleable {
  visibility: visible;
  max-height: 68px;
}

.toggleable {
  transition: visibility 1.5s ease-in-out, max-height .75s ease-in-out;
}

.toggler {
  cursor: pointer
}

nav {
  background: #e74c3c;
}

When I set the max-height to 68px (the height fitting two list items) it works perfectly, but when I set the max-height to 500px, for example, leaving room for future list items, it takes time to transition from 500 to 0, making it give a delay before the list items disappear again.

I do not wish to use scaling as it complicates it and I have to come up with a solution to solve the spacing under it. It keeps the spacing under the element and reserves it for when it opens out.

Upvotes: 0

Views: 1486

Answers (1)

Eljas
Eljas

Reputation: 1207

One workaround what I found was to use animation with @keyframes. Remember to add vendor-prefixes.

Browser support for this is the following: Firefox 5+, IE 10+, Chrome, Safari 4+, Opera 12+

I modified your CSS to this:

 .hide {
  visibility: hidden;
  overflow: hidden;
  max-height: 0;
}

input[type=checkbox]:checked~.toggleable {
  visibility: visible;
  animation: height1 .75s forwards;
}
input[type=checkbox]:not(:checked)~.toggleable {
  visibility: visible;
  animation: height2 .50s forwards;
}

.toggleable {
  transition: visibility 1.5s ease-in-out;
}

.toggler {
  cursor: pointer
}

nav {
  background: #e74c3c;
}
@keyframes height1 {
  0%   { max-height: 0; }
  100% { max-height: 500px; }
}
@keyframes height2 {
  0%   { max-height: 500px; }
  100% { max-height: 0; }
}

If used like this there will be smaller delay when clicking again.

Here is the updated jsfiddle: https://jsfiddle.net/m9pd8bjh/25/

Upvotes: 1

Related Questions