Layout · 02 of 23

Accordion

Smooth height expansion

HTML · CSS · JavaScript · No dependencies · MIT

HTML

<div class="accordion">
  <div class="acc-item">
    <div class="acc-header">Accordion Item 1</div>
    <div class="acc-content">
      <p>Content expands smoothly with height animation.</p>
    </div>
  </div>
  <div class="acc-item">
    <div class="acc-header">Accordion Item 2</div>
    <div class="acc-content">
      <p>More details revealed here.</p>
    </div>
  </div>
</div>

CSS

.accordion {
  width: 100%;
  max-width: 400px;
  color: #f0f0f5;
}

.acc-item {
  border-bottom: 1px solid rgba(255, 255, 255, 0.06);
}

.acc-header {
  padding: 1rem 0;
  cursor: pointer;
  font-weight: 600;
}

.acc-content {
  height: 0; /* JS animates this to the content's scrollHeight */
  overflow: hidden;
  color: #6b6b80;
  transition: height 0.4s cubic-bezier(0.16, 1, 0.3, 1);
}

JavaScript

var accItems = document.querySelectorAll('.acc-item');

accItems.forEach(function (item) {
  var header = item.querySelector('.acc-header');
  var content = item.querySelector('.acc-content');

  header.addEventListener('click', function () {
    var isActive = item.classList.contains('active');

    // Close all items first
    accItems.forEach(function (i) {
      i.classList.remove('active');
      i.querySelector('.acc-content').style.height = '0';
    });

    // Open the clicked one if it wasn't already open.
    // Animating to the measured scrollHeight lets CSS
    // transition height smoothly to an "auto"-like value.
    if (!isActive) {
      item.classList.add('active');
      content.style.height = content.scrollHeight + 'px';
    }
  });
});