Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using bootstrap template with vanilla web components

I have a traditional ASP.NET MVC web site, that uses the Metronic Bootstrap template.

Now, I'm thinking of rewriting this web site using the vanilla web components approach.

So I did a small test, and wrote a web component without shadow dom, and it seems my component just uses the Metronic style fine, so it inherits it from the parent page where I included it.

However, when I enable shadow DOM, then CSS propagation stops, and now my web component is not using the Metronic style anymore.

At this time I'm a bit uncertain on how to handle this situation: I can simply not use shadow DOM, but then, I'm not using the full strength and encapsulation of web components.

So how would you handle the situation where you have a large Bootstrap template that you want to use, in combination with web components? Is it worth it? Are there guidelines for this kind of situation?

like image 777
L-Four Avatar asked Jan 01 '23 10:01

L-Four


1 Answers

If you need to use a large CSS framework within ShadowDOM based Web Components then you need to include that CSS in each component or, at least, the portion of CSS needed for that component.

ShadowDOM was designed to prevent outside CSS from affecting the inner ShadowDOM. So, if you want specific CSS inside the ShadowDOM then you have to put it there.

The simplest thing to do is to include the <link> tag in your ShadowDOM. The same <link> tag you used outside of the components.

class MyElement extends HTMLElement {
  constructor() {
    super();
    let shadow = this.attachShadow({mode: 'open'});
    shadow.innerHTML = `
    <link href="my.css" rel="stylesheet">
    <h2 class="my-header">My Component</h2>
    <button class="my-button">Pay me</button>`;
  }
}

customElements.define('my-element', MyElement);
<link href="my.css" rel="stylesheet">
<div class="my-thing">Stuff</div>
<button class="my-button">Click me</button>
<hr/>
<my-element></my-element>

Since I don't have a file my.css you won't see the changes.

This will allow you to include the CSS in your page and also in your Components.

like image 86
Intervalia Avatar answered Jan 05 '23 17:01

Intervalia