logo

Render a template without shadow DOM in LitElement

February 27, 2021

In order to render a template without shadow DOM, you have to implement createRenderRoot and return this. This will enable you to access external styles.

Example

my-element.js

import {
  html,
  css,
  LitElement,
} from "https://unpkg.com/lit-element/lit-element.js?module";

export class MyElement extends LitElement {
  static get styles() {
    return css`
      h1 {
        background-color: red; /* will not work */
      }
    `;
  }
  createRenderRoot() {
    return this; // will render the template without shadow DOM
  }
  render() {
    return html` <h1>Hello World</h1> `;
  }
}

customElements.define("my-element", MyElement);

app.css

body {
  min-height: 100vh;
  display: grid;
  place-items: center;
  margin: 0;
  font-family: sans-serif;
  background-image: url("https://assets.codepen.io/3436988/background.png");
}

h1 {
  position: relative;
  text-transform: uppercase;
  color: #fff;
  font-size: 3rem;
}

h1::after {
  content: "";
  top: 0;
  left: 0;
  position: absolute;
  width: 50%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.3);
  backdrop-filter: blur(5px);
  -webkit-backdrop-filter: blur(5px);
}

I made a small demo, you can check the code on CodePen.

Your JS is turned off. Please turn it on to see the CodePen. Here's a screenshot from the Pen

Try reload the page, our check out the pen on CodePen.