Using External CSS Stylesheets for Custom Elements

javascript
Published on February 16, 2021

While creating a custom element, it is perfectly fine to use an external stylesheet for defining the element's CSS.

  • If a <template> is being used to define the custom element's HTML content, then include the stylesheet's <link> tag in it.

    <template id="input-plus-minus-template">
    	<!-- external stylesheet -->
    	<link href="css/custom-element.css" rel="stylesheet">
    	
    	<!-- HTML -->
    	<div id="container"></div>
    </template>
    
  • If stylesheet needs to be applied directly to the Shadow DOM, then create a new <link> element via Javascript.

    let style = document.createElement('link');
    style.setAttribute('rel', 'stylesheet');
    style.setAttribute('href', 'css/custom-element.css');
    
    // append stylesheet to Shadow DOM
    this.shadowRoot.append(style);
    
In this Tutorial