javascripthtmlcsstoggletransition

css toggle with transition effect for expanding div - set max-height to infinity alternative


There is a simple html+css+js code to expand/collapse div with a 1-second effect.

https://jsfiddle.net/zf1rd38y/3/

Css code looks simple:

.smalldesc {
  max-height: 52px;
  overflow: hidden;
  transition: all 1s ease;
  border: 1px solid red;
}

.smalldesc.expand {
  max-height: 150px;
}

The issue is here you see the max-height has a fixed value for .smalldesc.expand (but if the text is long enough, then not all text is displayed when expanded). If I set max-height: none; instead, then transition: all 1s ease; doesn't work.

Any ideas how to make it perfectly work for a very long text?


Solution

  • Using the view height ('vh', e.g. max-height: 100vh) seems to do the trick.

    See also

    document.querySelector('a').addEventListener('click', () =>
      document.querySelector(`.smalldesc`).classList.toggle(`expand`));
    .smalldesc {
      max-height: 50px;
      max-width: 50vw;
      overflow: hidden;
      border: 1px solid red;
      transition: all 1s ease;
      padding: 0.3rem;
    }
    
    .smalldesc.expand {
      max-height: 100vh;
      max-width: 80vw;
    }
    <h2>
      First text goes here.
    </h2>
    <div class="smalldesc">
      <a href="#">Read More</a>
      <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
        has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with ...</p>
    </div>
    <h2>
      Another text goes here.
    </h2>