How to use Material Design Icons in a web component?
Asked Answered
E

1

5

Looks like that mdi is not working inside web components, or do I miss something?

I want to develop a web component that encapsulates it's dependencies, adding the link to the parent document works, but it violates the original intent.

<html>
<body>
<x-webcomponent></x-webcomponent>
<script>
customElements.define(
  "x-webcomponent",
  class extends HTMLElement {
    constructor() {
      super();
      this.attachShadow({ mode: "open" });
      this.shadowRoot.innerHTML = `
        <style>@import url('https://cdn.materialdesignicons.com/4.9.95/css/materialdesignicons.min.css');</style>
        <span class="mdi mdi-home"></span>
      `;
    }
  }
);
</script>
</body>
</html>

https://codepen.io/Jamesgt/pen/MWwvJaw

Embark answered 3/3, 2020 at 9:50 Comment(5)
Looks like that css @import is not working and I guess because it refers other resources also...Embark
Does this answer your question? How to let imported css have effects on elements in the shadow dom?Alliber
add the <link> in the main document, tooAlliber
Thanks, edited the question, <link> in outer doc helps, but I don't feel it an elegant solution.Embark
maybe it seems inelegant but it's the only solution using font by now...Alliber
A
3

The @font-face CSS at-rule for the font you want to use must be declared in the main document, not in the Shadow DOM.

Because in your case it is defined in the materialdesignicons.min.css file, you'll need to load it in the main document via a global <link>.

Note that the CSS file won't be loaded twice thanks to the browser's cache.

Alternately, you could add it in the light DOM of the web component, or you could just declare the @font-face at-rule (copied from the materialdesignicons.css file).

Here is a running example:

customElements.define( "x-webcomponent", class extends HTMLElement {
    constructor() {
      super()
      this.attachShadow({ mode: "open" })
      this.shadowRoot.innerHTML = `
        <link rel=stylesheet  href=https://cdn.materialdesignicons.com/4.9.95/css/materialdesignicons.min.css>
        <span class="mdi mdi-home"></span>`
    }
    connectedCallback () {
      this.innerHTML = `<style>
          @font-face {
            font-family: "Material Design Icons";
            src: url("https://cdn.materialdesignicons.com/4.9.95/fonts/materialdesignicons-webfont.woff?v=4.9.95") format("woff");
          }
       </style>`
    }
} )
<x-webcomponent></x-webcomponent>
Alliber answered 4/3, 2020 at 12:37 Comment(2)
note that in the snippet example I've added only the font that work for Firefox and Chrome on Windows. Maybe you'll need to add another font format for Safari and/or Apple / LinuxAlliber
note also that putting font-faceor linkin the light DOM will be redundant if you insert multiple instances of the custom element in the same page/iframeAlliber

© 2022 - 2024 — McMap. All rights reserved.