Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk3 min

How to Make a Show More/Less Div Expand Smoothly

Animate a collapsible div between measured pixel heights instead of relying on height:auto. Learn how to keep button state accessible and accommodate reduced motion and changing content.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a smooth expanding div, animate between explicit pixel heights—not from height: 0 to height: auto. Measure the content with JavaScript’s scrollHeight, use a real button to control the panel, and account for keyboard access, reduced motion, and content changes.

Why height: auto does not animate reliably

CSS transitions interpolate between values the browser can calculate. auto is not a fixed numeric endpoint, so a transition to or from it can be unpredictable. Set a numeric height for both ends of the transition instead. MDN’s guide to CSS transitions explains how transitions behave.

As an Amazon Associate I earn from qualifying purchases.

Build a measured-height disclosure

This pattern measures the panel’s content, transitions to that pixel height when opening, and returns to zero when closing. It uses a native button and exposes the open state through aria-expanded.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<button type="button" aria-expanded="false" aria-controls="more-info">
  Show more
</button>
<div id="more-info" class="more-content">
  <p>Additional information goes here.</p>
</div>

<style>
  .more-content {
    height: 0;
    overflow: hidden;
    transition: height 250ms ease;
  }

  @media (prefers-reduced-motion: reduce) {
    .more-content {
      transition: none;
    }
  }
</style>

<script>
  const button = document.querySelector('[aria-controls="more-info"]');
  const panel = document.getElementById('more-info');
  let isOpen = false;

  button.addEventListener('click', () => {
    isOpen = !isOpen;
    button.setAttribute('aria-expanded', String(isOpen));
    button.textContent = isOpen ? 'Show less' : 'Show more';

    if (isOpen) {
      panel.style.height = `${panel.scrollHeight}px`;
      panel.addEventListener('transitionend', function onOpen(event) {
        if (event.propertyName !== 'height') return;
        panel.style.height = 'auto';
        panel.removeEventListener('transitionend', onOpen);
      });
    } else {
      panel.style.height = `${panel.scrollHeight}px`;
      requestAnimationFrame(() => {
        panel.style.height = '0px';
      });
    }
  });
</script>

The opening transition ends at a measured height; after it completes, the script changes the height to auto so the open panel can reflow as its contents change. The closing handler first sets the current content height, then schedules the transition to zero on the next animation frame. This avoids trying to animate directly from auto.

#1 Best Overall
Sale
HTML and CSS: Design and Build Websites
  • HTML CSS Design and Build Web Sites
  • Comes with secure packaging
  • It can be a gift option

Keep the accessible state in sync

  • Use a <button type="button">, which works with keyboard activation, rather than a clickable generic element.
  • Keep aria-controls pointed at the panel’s unique ID and update aria-expanded on every toggle.
  • Change the button label to “Show less” while the panel is open, then back to “Show more” when closed.
  • Do not apply hidden or display: none before the closing animation finishes. That removes the panel from the accessibility tree and prevents it from animating. MDN documents the accessibility effect of display: none.

The example assumes the panel is initially collapsed and has no competing script changing its height. If the content changes while open, the temporary auto height allows it to reflow. Before a later close, the handler measures the current content again. If you need to keep an explicit height while content changes, use a ResizeObserver to update it.

Choose between JavaScript height and CSS max-height

Approach Animation control Dynamic content and clipping Trade-off
Measured numeric height with JavaScript Transitions to the panel’s measured height. Can measure variable content; remove the temporary fixed height after opening so content can reflow. More implementation and state management, but gives the most predictable height animation.
CSS max-height Can transition between a collapsed value and a chosen maximum. Can clip content if the maximum is too small. If the maximum is much larger than the content, the perceived timing may not match the visible expansion. Simpler when there is a trustworthy upper bound on content height.

A CSS-only max-height transition is reasonable for short, bounded content. For content of varying length, measuring the actual height avoids choosing an arbitrary ceiling. These trade-offs follow from animating numeric dimensions rather than relying on auto.

Use native details when custom animation is not necessary

<details> and <summary> provide built-in disclosure semantics and browser-managed open and closed states:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<details>
  <summary>Show more</summary>
  <p>Additional information goes here.</p>
</details>

The element can also be opened or closed by script, but it has no built-in transition between those states. Choose it when native disclosure behavior matters more than a custom expansion animation. MDN’s <details> reference describes its behavior.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Respect reduced motion and text resizing

The @media (prefers-reduced-motion: reduce) rule in the example removes the transition for users whose operating system requests less non-essential motion. The content and button states should remain the same when motion is disabled; only the animation changes. MDN explains the reduced-motion preference.

Test the panel with zoom and larger text, too. A fixed height that is adequate at the default text size may obscure content after text is enlarged. Using auto while the panel is open helps it adapt; do not leave a fixed expanded height in place unless you update it when content or layout changes. MDN’s height reference covers height values and their behavior.

Rank #4
Sale
Web Design with HTML, CSS, JavaScript and jQuery Set
  • Brand: Wiley
  • Set of 2 Volumes
  • A handy two-book set that uniquely combines related technologies Highly visual format and accessible language makes these books highly effective learning tools Perfect for beginning web designers and front-end developers

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.