How to Override CSS in a Shadow Dom/Web Component

Cesar William Alvarenga
Level Up Coding
Published in
3 min readSep 1, 2020

--

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.

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>

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.

Override Attempt

In this example, we want to modify the background color of the card. If it was a simple div element in your HTML, you could override the card class or via CSS selectors to access the div element. But the following attempts won’t work:

--

--