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?
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.