IMLC
Home/html/animation-expand
Article

Expand Animation

L
Lawrence
|Reading time

Expand Animation

Expand animations reveal content smoothly by expanding an element's height, width, or both. They're commonly used in accordions, dropdown menus, collapsible sections, and modal dialogs.

Why Use Expand Animations?

  • Provide visual feedback when showing/hiding content
  • Draw attention to newly revealed information
  • Create smoother user experience compared to instant visibility changes
  • Guide users through progressive disclosure

Basic Height Animation

The classic approach uses `max-height`:

css
.expandable {
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.3s ease-out;
}

.expandable.open {
  max-height: 500px; /* Arbitrary large value */
}
html
<div class="expandable" id="mySection">
  <p>This content will expand when visible.</p>
</div>
<button onclick="toggleExpand()">Toggle</button>

<script>
  function toggleExpand() {
    document.getElementById('mySection').classList.toggle('open');
  }
</script>

Problem with max-height

The `max-height` approach has a limitation - you need to guess an appropriate maximum value. If too small, content gets cut off. Too large causes unnecessary animation time.

Better Approach: CSS Grid

Use CSS Grid to animate to `grid-template-rows: 0fr` then `1fr`:

css
.expandable {
  display: grid;
  grid-template-rows: 0fr;
  transition: grid-template-rows 0.3s ease-out;
}

.expandable.open {
  grid-template-rows: 1fr;
}

.expandable-inner {
  overflow: hidden;
}
html
<div class="expandable" id="mySection">
  <div class="expandable-inner">
    <p>This content expands smoothly!</p>
  </div>
</div>

Auto-Animate Height with JavaScript

For true auto-height animation, use JavaScript to measure content:

javascript
function toggleExpand(element) {
  if (element.style.maxHeight) {
    element.style.maxHeight = '';
  } else {
    element.style.maxHeight = element.scrollHeight + 'px';
  }
}
css
.expandable {
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.3s ease-out;
}

Width Animation

Animate width for horizontal expand effects:

css
.expandable {
  width: 0;
  overflow: hidden;
  transition: width 0.3s ease-out;
  white-space: nowrap;
}

.expandable.open {
  width: 300px;
}

Demo

Try the interactive demo on the right! Click the boxes to expand/collapse them.

Tips

  • Use `ease-out` for expanding, `ease-in` for collapsing
  • Consider adding `will-change` for performance optimization
  • The grid method is the most modern and reliable CSS-only approach
  • Test animations on mobile devices - faster durations often work better