Apply CSS Styles To A Web Component
Deatils
- All of the pages I saw on how to Style CSS components were overly complex. Here's what works for me.
Example
HTML
<styled-component></styled-component>
JavaScript
class StyledComponent extends HTMLElement {
constructor() {
super()
this.attachShadow({ mode: 'open' })
const styles = document.createElement('style')
styles.innerText = `
span{
background: #123423;
color: #873742;
font-size: 2rem;
}`
const content = document.createElement('span')
content.innerText = 'bravo'
this.shadowRoot.append(styles)
this.shadowRoot.append(content)
}
}
customElements.define('styled-component', StyledComponent)
Notes
- It doesn't sound like you can style the compenets directly, but I think you could pass in values maybe?
References