1

I have

main.js and index.html below

class CustomTagA extends HTMLElement {
      constructor() {
        super();

        const shadow = this.attachShadow({mode: 'open'});
        const wrapper = document.createElement('h1');
        wrapper.setAttribute('class', 'wrapper');
        wrapper.textContent = 'Custom Tag A';
        shadow.appendChild(wrapper);
      }
}

class CustomTagB extends HTMLElement {
  constructor() {
       super();

    const shadow = this.attachShadow({mode: 'open'});

    const wrapper = document.createElement('a');
    wrapper.setAttribute('class', 'wrapper');
    wrapper.textContent = 'Custom Tag B';
     shadow.appendChild(wrapper);
  }
}

customElements.define('cutomtag-a', CustomTagA);
customElements.define('cutomtag-b', CustomTagB);
<!DOCTYPE html>
<html lang="en">
<head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
</head>
<body>
      <cutomtag-a></cutomtag-a>
      <cutomtag-b></cutomtag-b>
      <script src="./main.js"></script>
</body>
</html>

When my code running on browser i have inpect html and discover them. I have few questions about Shadow Element

  1. Where default css of Shadow Host Element?
  2. Why cutomtag-a beak line while it display Inline? Is it because i use h1 tag?What is their working principle? Where can I find documents?
Minh Sự
  • 97
  • 2
  • 8

1 Answers1

1

shadowDOM is styled with <style> definitions inside shadowDOM

Or, when using <slot> see (long) SO post: ::slotted CSS selector for nested children in shadowDOM slot

<!-- YOUR JS FILE -->
<script>
  customElements.define('my-element', class extends HTMLElement {
    constructor() {
      super().attachShadow({mode:'open'})
             .append(document.getElementById(this.nodeName).content.cloneNode(true))
    }
  });
</script>

<!-- YOUR HTML FILE -->
<template id="MY-ELEMENT">
  <!-- goes into shadowDOM -->
  <style>
    h1 {
      background: green;
    }
  </style>
  <h1>Web Component!</h1>
</template>

<style>
  body {
    background: coral;
    color: gold; /* inheritable styles do style shadowDOM */
  }
</style>

<h1>Hello</h1>
<my-element></my-element>
Danny '365CSI' Engelman
  • 16,526
  • 2
  • 32
  • 49