0

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/bootstrap@5.0.2/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.

Luke Vo
  • 17,859
  • 21
  • 105
  • 181

1 Answers1

1

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/bootstrap@5.0.2/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/bootstrap@5.3.0/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>
Luke Vo
  • 17,859
  • 21
  • 105
  • 181
isherwood
  • 58,414
  • 16
  • 114
  • 157
  • 1
    Sorry for the late response. Thank you very much this is very helpful. I found out a simple CSS for Bootstrap 5.2+ to toggle the arrow. I hope you are okay with me editing your answer to add it. – Luke Vo Jun 07 '23 at 12:17