Skip to main contentSkip to docs navigation

Create smooth, accessible content toggles with Chassis CSS's collapse component, featuring height and width animations with comprehensive JavaScript controls.

@layer components
Requires JavaScript
Context tokens

Introduction

Collapse components provide flexible content visibility toggles using CSS transforms for smooth animations. The component supports multiple trigger-target relationships and requires explicit initialization for optimal performance.

How it work

Chassis CSS collapse uses JavaScript to show and hide content through smooth transitions. Buttons or links serve as triggers that control specific collapsible elements. The component animates height or width from its current value to zero using CSS transforms for optimal performance. Due to CSS animation constraints, avoid applying padding directly to .collapse elements and use the class as an independent wrapper instead.

Chassis CSS respects user accessibility preferences by automatically disabling animations when the prefers-reduced-motion media query is detected. See the reduced motion guidelines in our accessibility documentation for implementation details.

Examples

Explore practical collapse implementations showcasing Chassis CSS's flexible architecture and comprehensive feature set. These examples demonstrate real-world usage patterns from basic content toggles to complex multi-target interactions.

Basic structure

This foundational example demonstrates essential collapse functionality with multiple trigger types. Chassis CSS supports both button and link triggers, though semantic <button> elements are recommended for optimal accessibility.

The .collapse class hides content by default, .collapsing is applied during transition animations, and .collapse.show displays content in expanded state. Chassis CSS recommends semantic <button> elements with data-cx-target attributes. Link elements (<a>) with href attributes are supported but require role="button" for accessibility. Both approaches require data-cx-toggle="collapse".

Some placeholder content for the collapse component. This panel is hidden by default but revealed when the user activates the relevant trigger.
HTML
<p class="d-inline-flex gap-2xsmall">
  <a class="button primary" data-cx-toggle="collapse" href="#collapseExample" role="button" aria-expanded="false" aria-controls="collapseExample">
    Link with href
  </a>
  <button class="button primary" type="button" data-cx-toggle="collapse" data-cx-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
    Button with data-cx-target
  </button>
</p>
<div class="collapse" id="collapseExample">
  <div class="card card-body">
    Some placeholder content for the collapse component. This panel is hidden by default but revealed when the user activates the relevant trigger.
  </div>
</div>

Horizontal collapse

Transform collapse behavior for width-based animations using .collapse-horizontal. This modifier transitions element width instead of height, enabling sophisticated layout patterns and responsive design implementations.

Set explicit width values on immediate child elements using Chassis CSS width utilities, custom CSS, or inline styles for width control.

The example below includes min-height styling to prevent layout shifts in documentation. In production implementations, only the child element's width property is required for proper horizontal collapse functionality.

This is some placeholder content for a horizontal collapse. It's hidden by default and shown when triggered.
HTML
<p>
  <button class="button primary" type="button" data-cx-toggle="collapse" data-cx-target="#collapseWidthExample" aria-expanded="false" aria-controls="collapseWidthExample">
    Toggle width collapse
  </button>
</p>
<div style="min-height: 120px;">
  <div class="collapse collapse-horizontal" id="collapseWidthExample">
    <div class="card card-body" style="width: 300px;">
      This is some placeholder content for a horizontal collapse. It's hidden by default and shown when triggered.
    </div>
  </div>
</div>

Multiple targets and triggers

Demonstrate advanced collapse functionality with complex trigger-target relationships. Single triggers can control multiple elements, and multiple triggers can control individual elements, enabling sophisticated interface patterns.

Use CSS selectors in data-cx-target or href attributes to control multiple collapse elements simultaneously. Reference the same target element from multiple triggers using consistent data-cx-target or href values for flexible interface control.

Some placeholder content for the first collapse component of this multi-collapse example. This panel is hidden by default but revealed when the user activates the relevant trigger.
Some placeholder content for the second collapse component of this multi-collapse example. This panel is hidden by default but revealed when the user activates the relevant trigger.
HTML
<p class="d-inline-flex gap-2xsmall">
  <button type="button" class="button primary" data-cx-toggle="collapse" data-cx-target="#multiCollapseExample1" aria-expanded="false" aria-controls="multiCollapseExample1">Toggle first element</button>
  <button class="button primary" type="button" data-cx-toggle="collapse" data-cx-target="#multiCollapseExample2" aria-expanded="false" aria-controls="multiCollapseExample2">Toggle second element</button>
  <button class="button primary" type="button" data-cx-toggle="collapse" data-cx-target=".multi-collapse" aria-expanded="false" aria-controls="multiCollapseExample1 multiCollapseExample2">Toggle both elements</button>
</p>
<div class="row">
  <div class="col">
    <div class="collapse multi-collapse" id="multiCollapseExample1">
      <div class="card card-body">
        Some placeholder content for the first collapse component of this multi-collapse example. This panel is hidden by default but revealed when the user activates the relevant trigger.
      </div>
    </div>
  </div>
  <div class="col">
    <div class="collapse multi-collapse" id="multiCollapseExample2">
      <div class="card card-body">
        Some placeholder content for the second collapse component of this multi-collapse example. This panel is hidden by default but revealed when the user activates the relevant trigger.
      </div>
    </div>
  </div>
</div>

Accessibility

Collapse components in Chassis CSS prioritize accessibility through semantic markup, proper ARIA attributes, and keyboard navigation support. These features ensure collapse functionality enhances rather than hinders the user experience for all users.

ARIA attributes

Proper ARIA implementation ensures collapse components communicate state changes effectively to assistive technologies. The aria-expanded attribute explicitly conveys current collapse state to screen readers and is required on control elements. For single targets, include aria-controls with target element IDs to enable assistive technology navigation shortcuts. When using non-button elements (like <a> or <div>) as triggers, add role="button" for proper semantic meaning.

Chassis CSS automatically updates aria-expanded values based on collapse state changes, maintaining accessibility compliance without manual intervention.

Keyboard navigation

Chassis CSS collapse supports standard keyboard interaction patterns for comprehensive accessibility. All collapse triggers respond to standard button activation methods (Space, Enter keys) when properly implemented with semantic button elements. Focus remains on trigger elements after activation, maintaining predictable navigation patterns for keyboard users.

Implementation guidelines

Follow these practices to ensure collapse components remain accessible across all user scenarios. Prioritize <button> elements for triggers to ensure inherent keyboard accessibility and proper screen reader announcement. When controlling single elements, always include aria-controls with target element IDs to enable assistive technology navigation shortcuts.

For advanced keyboard patterns (like accordion-style navigation), implement custom JavaScript following ARIA Authoring Practices Guide accordion patterns as Chassis CSS focuses on core collapse functionality.

CSS

This component can be customized through Sass variables at compile time.

Sass variables

This component uses Sass variables in scss/config/_defaults.scss to define its defaults.

$transition-collapse:       height .35s ease;
$transition-collapse-width: width .35s ease;

Classes

Collapse animation states are defined in scss/_transitions.scss as these classes are shared across multiple components (collapse and accordion).

.collapse {
  &:not(.show) {
    display: none;
  }
}

.collapsing {
  height: 0;
  overflow: hidden;
  @include transition($transition-collapse);

  &.collapse-horizontal {
    width: 0;
    height: auto;
    @include transition($transition-collapse-width);
  }
}

JavaScript API

Chassis CSS collapse provides comprehensive JavaScript controls for dynamic content management. The API supports both declarative data attributes and programmatic initialization for flexible integration with modern applications.

Data attributes

Implement collapse functionality using declarative HTML data attributes for streamlined initialization and configuration. Add data-cx-toggle="collapse" and data-cx-target to control elements for automatic collapse binding. The data-cx-target attribute accepts CSS selectors to control one or more collapsible elements.

Apply the collapse class to collapsible elements. Add the show class for elements that should be expanded by default. For accordion-style group management where opening one element closes others, add data-cx-parent="#selector". Refer to the accordion documentation for comprehensive group control patterns.

Initialization

Initialize collapse components programmatically for dynamic content or advanced configuration requirements.

JavaScript
const collapseElementList = document.querySelectorAll('.collapse')
const collapseList = [...collapseElementList].map(collapseEl => new chassis.Collapse(collapseEl))

You can create a collapse instance with the constructor, for example:

JavaScript
const cxCollapse = new chassis.Collapse('#myCollapse', {
  toggle: false
})

Configuration options

Options are set via data-cx-* attributes or passed to the constructor as an object. Attribute names use the kebab-case form of the option name — data-cx-custom-class, not data-cx-customClass. Attribute values are parsed to their native types:"true"true, "0"0, and valid JSON strings to objects.

Use data-cx-config to pass multiple options as a JSON string:data-cx-config='{"delay":200}'. Individual data-cx-* attributes take precedence over data-cx-config. You can also use JSON values in individual attributes, such as data-cx-delay='{"show":100,"hide":200}'.

When initializing components, Chassis merges configurations from multiple sources in this priority order: default settings, data-cx-config values, individual data-cx-*attributes, and finally any JavaScript object options. Values defined later in this sequence override earlier ones.

NameTypeDefaultDescription
parentselector, DOM elementnullIf parent is provided, then all collapsible elements under the specified parent will be closed when this collapsible item is shown. (similar to traditional accordion behavior - this is dependent on the card class). The attribute has to be set on the target collapsible area.
togglebooleantrueToggles the collapsible element on invocation.

Methods

Chassis CSS collapse provides comprehensive instance methods for programmatic control and integration with application logic:

All Chassis CSS component methods are asynchronous and initiate CSS transitions. Methods return immediately when the transition begins, not when it completes. Calling methods on components that are already transitioning will be ignored to prevent conflicts. Learn more about Chassis JavaScript patterns.

MethodDescription
disposeDestroys an element's collapse. (Removes stored data on the DOM element)
getInstanceStatic method which allows you to get the collapse instance associated to a DOM element, you can use it like this: chassis.Collapse.getInstance(element).
getOrCreateInstanceStatic method which returns a collapse instance associated to a DOM element or create a new one in case it wasn't initialized. You can use it like this: chassis.Collapse.getOrCreateInstance(element).
hideHides a collapsible element. Returns to the caller before the collapsible element has actually been hidden (e.g., before the hidden.cx.collapse event occurs).
showShows a collapsible element. Returns to the caller before the collapsible element has actually been shown (e.g., before the shown.cx.collapse event occurs).
toggleToggles a collapsible element to shown or hidden. Returns to the caller before the collapsible element has actually been shown or hidden (i.e. before the shown.cx.collapse or hidden.cx.collapse event occurs).

Events

Chassis CSS collapse exposes comprehensive events for hooking into collapse functionality and integrating with application logic:

Event typeDescription
hide.cx.collapseThis event is fired immediately when the hide method has been called.
hidden.cx.collapseThis event is fired when a collapse element has been hidden from the user (will wait for CSS transitions to complete).
show.cx.collapseThis event fires immediately when the show instance method is called.
shown.cx.collapseThis event is fired when a collapse element has been made visible to the user (will wait for CSS transitions to complete).
JavaScript
const myCollapsible = document.getElementById('myCollapsible')
myCollapsible.addEventListener('hidden.cx.collapse', event => {
  // do something...
})