Search code examples
cssweb-componentlit

Why is my nested web component adding vertical space in Lit?


I have a weird issue where when I add padding-left: 32px to an element, vertical space gets added. If the CSS says 0, and I add the space manually in Chrome debugger, the vertical space isn't there. This is only happening with nested components. I'm not sure if I'm misusing something or if I have found a bug.

I have code like this:

<cai-setting-row class="itemGroupMiddle doubleIndent" data-type="A"
  >Not Nested A</cai-setting-row
><cai-setting-row class="itemGroupMiddle doubleIndent" data-type="A"
  >Not Nested B</cai-setting-row
>

<cai-setting-row-account></cai-setting-row-account>

The render of cai-setting-row-account is just the same markup:

render() {
  return html`<cai-setting-row
        class="itemGroupMiddle doubleIndent"
        data-type="A"
        >Nested A</cai-setting-row
      ><cai-setting-row class="itemGroupMiddle doubleIndent" data-type="A"
        >Nested B</cai-setting-row
      >`;
}

It renders like this:

enter image description here

The "Not Nested" elements look right. The "Nested" ones have extra space and you can see a weird border on top that is the distance of the padding.

I have a functioning sandbox here:

https://studio.webcomponents.dev/edit/8u0cg76BNEiSoHXQT8by/


Solution

  • I misunderstood how class is used on a custom component. Doing <my-component class="foo"> adds foo to the :host. My code in sandbox needed to change the magic of const parentClass = this.getAttribute('class') ?? ''; to const parentClass = this.getAttribute('itemClass') ?? '';, such that I wouldn't accidentally be applying classes to the :host and the intended element.