1

I'm making a web component in Javascript and called it NavBar, all the style for the new custom HTML tag is in one CSS file, which name is "style.css". I tried to import it in this way and it didn't work:

this.innerHTML = `
  <style>
    @import "style.css";
  </style>
  <nav>
    ...code...
  </nav>
`;
}

Can I know why this way didn't work, and what is the right way to import the Stylesheet? Thanks.

Umutambyi Gad
  • 4,082
  • 3
  • 18
  • 39
Hasan
  • 155
  • 1
  • 2
  • 13

2 Answers2

2

Although the Stylesheet is in the same directory of the NavBar.js file, the directory import path should be different and related to the HTML file that uses the new HTML tag: <nav-bar></nav-bar>. for example, when I want to use the nav-bar tag in my index.html file, the import path should be: @import "./modules/nav-bar/style.css" This problem will prevent me from using the new tag in different HTML files. I hope that I find a solution for generating different pathes for each specific file.

Hasan
  • 155
  • 1
  • 2
  • 13
2

In general @import is considered convenient but not preferred, see all the import VS link blogs.

Use:

  • <link>
  • inline your CSS in the STYLE tag
  • (fetch (also async) the CSS file and write it to the STYLE tag)

Most convenient?, because you are writing CSS in a STYLE tag and not in a text string,
might be to work from a <TEMPLATE> with inline CSS

<template id="MY-ELEMENT">
  <style id=custom></style>
  <style>
    :host() {
      display: inline-block;
    }
    span{
      font-size:3em;
      color: var(--color);
    }
  </style>
  <span>
    <slot></slot>
  </span>
</template>
<script>
  customElements.define('my-element', class extends HTMLElement {
    connectedCallback() {
      this.attachShadow({mode: 'open'})
          .append(
            document.getElementById(this.nodeName).content.cloneNode(true)
          );
      const color = `:host{--color:${this.getAttribute("color")}}`;
      this.shadowRoot.getElementById("custom").sheet.insertRule(color,0);
    }
  });
</script>
<my-element color=red>Hello</my-element>
<my-element color=green>World</my-element>

Also see:

Danny '365CSI' Engelman
  • 16,526
  • 2
  • 32
  • 49
  • Thanl you, I'll probably change the way of importing sttylesheets as you said to prevent future problems. – Hasan Aug 02 '20 at 07:31