1

I have a custom component that allows the parent component to use a modal dialog. The component has a slot that the caller can use to customize the content in the body. We've found a use case where we want the hight to be manually set. I've been able to do this within the component by using the following CSS:

.slds-modal__content {
    height: 920px;
}

The problem is I only want this to apply if the caller sends a height parameter. A technique I've used before to allow customized styles is calculated classes. The HTML has something like this:

<div class={containerClasses}>

And then the JS would be something like:

@api height = null;
get containerClasses() {
    return 'slds-modal__content' + (height ? ` manual-height` : '');
}

But to get to that point I experimented with renaming the selector to 'manual-height' in the CSS and adding the class to the HTML:

<div class="slds-modal__container manual-height">

But when I do this the height is no longer applied. Returning the CSS selector to just the SLDS class returns the manual height.

How can I get the height of the div to work with a selector other than slds-modal__container?

1 Answer 1

2

Add a variable to your CSS:

.slds-modal__content {
    height: var(--modal-height, 920px);
}

Now, in the component that wants to set the height, it can do so:

@api height = null;
renderedCallback() {
  if(this.height) {
    this.template.host.style.setAttribute('--modal-height', this.height);
  } else {
    this.template.host.style.removeAttribute('--modal-height');
  }
}

Now, you get the default height for all components that don't have the variable set, and you get the custom height for those that do. This example requires the units to be specified (e.g. height="250px").

3
  • Thanks for such a complete answer. It's getting me on a new track to solve this. FYI, as given, I am getting an error setAttribute is undefined at the time it's being called, which I'm assuming is because at the point of setting it, the page hasn't rendered the element. Looking how to solve that next.
    – Chuck
    Commented May 14 at 1:55
  • @Chuck Fair point. You may want to use renderedCallback instead. I'll edit.
    – sfdcfox
    Commented May 14 at 2:13
  • We were still getting errors, even when I added a check for isModalOpen, which determines if the modal is shown or not. We got it to work by attaching a style attribute to the div with a conditional value from the JS if a manual height was passed.
    – Chuck
    Commented May 15 at 23:19

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .