Luke Vo
Luke Vo

Reputation: 20668

Can I apply Bootstrap's Accordion or Alert styles to HTML details and summary elements?

My projects use Bootstrap and most of the time without any Javascript because I only need the styling. Now I have a project that needs something like their Accordion which needs Javascript to work. However there is a standard <details> HTML tag that can do that. The problem is I cannot really apply Accordion styling to it.

This is my best attempt so far but the accordion-header simply wraps all the body as well:

<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>

<div class="accordion">
    <details class="accordion-item">
        <summary class="">
            <div class="accordion-header">
                Title
            </div>
        </summary>

        <div class="accordion-body">
            <p>This is the body</p>
        </div>
    </details>
</div>

An alternative would be somehow making the summary look like an .alert.

Upvotes: 1

Views: 761

Answers (1)

isherwood
isherwood

Reputation: 61083

I'm not exactly sure what you meant by the header wrapping the body, but putting the accordion-button class on the title element gets you close. The icon doesn't flip, though. That would require JavaScript or a custom CSS solution.

<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />

<div class="accordion m-4">
  <details class="accordion-item">
    <summary class="accordion-button">
      <div class="accordion-header">
        Title
      </div>
    </summary>

    <div class="accordion-body">
      <p>This is the body</p>
    </div>
  </details>
</div>


For Bootstrap 5.2+ where Accordion CSS variables are supported, you can add these CSS so the arrow changes as user opens/closes it:

details.accordion-item:not([open]) .accordion-button {
    background-color: var(--bs-accordion-bg);
}

details.accordion-item:not([open]) .accordion-button::after {
    background-image: var(--bs-accordion-btn-active-icon);
    transform: unset;
}

details.accordion-item[open] .accordion-button::after {
    background-image: var(--bs-accordion-btn-icon);
    transform: var(--bs-accordion-btn-icon-transform);
}
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />

<div class="accordion m-4">
  <details class="accordion-item">
    <summary class="accordion-button">
      <div class="accordion-header">
        Title
      </div>
    </summary>

    <div class="accordion-body">
      <p>This is the body</p>
    </div>
  </details>
</div>

Upvotes: 4

Related Questions