One of the main purposes of Web Components is to provide encapsulation — being able keeping the markup structure and style hidden and separate from other code on the page so that different parts do not clash; this way the code can be kept nice and clean.

Shadow DOM gives us scoped style encapsulation and a means to let in as much (or as little) of the outside world as we choose.

But what if I want to make my component customizable for some style properties?

This article covers the basics of using CSS Custom Properties to penetrate the Shadow DOM and let your web component be customizable.

Creating an HTML Element

We will create our custom HTML element using a JavaScript class that extends the base HTMLElement. Then we will call customElements.define()with the tag name we want to create and the class that we just created.

class AppCard extends HTMLElement {...}

	window.customElements.define('app-card', AppCard);

In this example, we will create this simple Material Design card. It will be shown when we add this element on an HTML: <app-card></app-card>

Image for post

First, we create the Shadow DOM root, and then we assign the HTML and CSS string to the Shadow DOM root innerHTML, as shown below.

class AppCard extends HTMLElement {
	  constructor() {
	    super();

	    const shadowRoot = this.attachShadow({mode: 'open'});

	    shadowRoot.innerHTML = `
	      <style>
	        .card {
	          background-color: #fff;
	          ...
	        }
	      </style>
	      <div class="card">
	        <div>Card title</div>
	      </div>
	    `;
	  }
	}

	window.customElements.define('app-card', AppCard);

#web-components #javascript #shadow-dom #css #custom-elements

How to Override CSS in a Shadow Dom/Web Component
47.05 GEEK