[SalesForce] LWC lightning-accordion how to change CSS of the summary heading for open sections

I have an accordion implemented in lightning data table, and I want to change the style (background color) of the accordion Summary whenever the section is opened.
I didn't know how to implement a CSS for the opened section.
I tried the (Styling Hooks) below but it didn't work:

.THIS .slds-is-open > .slds-accordion__summary-heading {
  background-color: var(--sds-c-accordion-summary-color-background, red);
  }

Best Answer

That's now how that works. You should specify the selector to use, and the hook you wish to modify. Normally, this will be something like:

.slds-is-open {
  --sds-c-accordion-summary-color-background: red;
}

The documentation explains how it works in the background, using the CSS var() function, but the part you need to focus on is setting the value.


To get this to work, you have to set a property you have access to. After some experimentation, I came up with the following code:

import { LightningElement } from "lwc";

export default class Q320026lwc extends LightningElement {
  sections = [
    { title: "Section 1", body: "Section 1 Content", id: "1" },
    { title: "Section 2", body: "Section 2 Content", id: "2" },
    { title: "Section 3", body: "Section 3 Content", id: "3" },
    { title: "Section 4", body: "Section 4 Content", id: "4" },
  ];
  onsectiontoggle(event) {
    let openSections = event.detail.openSections;
    let sections = this.template.querySelectorAll(
      "lightning-accordion-section"
    );
    sections.forEach((section) => {
      section.dataset.open = !!(openSections.indexOf(section.name) > -1);
    });
  }
}

<template>
    <lightning-accordion onsectiontoggle={onsectiontoggle}>
        <lightning-accordion-section name={section.id} label={section.title} for:each={sections} for:item="section"
            key={section.id}>
            {section.body}
        </lightning-accordion-section>
    </lightning-accordion>
</template>

[data-open="true"] {
  --sds-c-accordion-summary-color-background: red;
}

We use the sectiontoggle event to determine what's open, then attach a custom data element to the section. We can use this attribute to trigger the custom CSS.

Related Topic