1

I have some very basic code like this

#component file
import { html, LitElement } from 'lit';
import sheet from './css/styles.js';

export class CaiWc extends LitElement {
  static styles = [sheet];

  render() {
    return html`
      <h2>Hello World</h2>
      <div>ITEM 1</div>
      <div>ITEM 2</div>
      <div>ITEM 3</div>
    `;
  }
}
#styles.js
import { css } from 'lit';

export default css`
  :root {
    background-color: #0000cc;
    color: #ff0000;
  }

  :host {
    background-color: #ff0000;
    color: #0000cc;
  }
`;

I don't understand why no background colors are showing up. When my markup was more complex with a third party web component, that web component would have the background color set from :host. If I read https://developer.mozilla.org/en-US/docs/Web/CSS/background-color correctly, background color isn't inherited. However if the default is transparent, why isn't it filling in?

chrome inspector showing a web component taking space with a set background color, yet not background color is used. the font color works as expected

Dave Stein
  • 8,653
  • 13
  • 56
  • 104

1 Answers1

4

By default, the custom element host defaults to display: inline - which results in the background-color not showing up. Additionally setting width and height would have no effect.

Adding display: block; or display: inline-block; to your :host styles should fix the issue, recommended by these Custom Element Best Practices.

There is also some discussion around this behavior in this Github issue: Should shadow host have display: block by default. And followup discussion around resolving this issue: Provide a lightweight mechanism to add styles to a custom element.

YouCodeThings
  • 590
  • 3
  • 13
  • Thanks, Chrome inspector showing the whole area lit up misled me a bit. Would have never guessed about the inline thing and didn't see anything about it with my Google search! – Dave Stein Nov 02 '22 at 14:22