preactjs / preact-custom-element

Wrap your component up as a custom element
MIT License
360 stars 52 forks source link

host css styles applied to component? #87

Closed da1z closed 5 months ago

da1z commented 5 months ago

Am I doing something wrong? as i understand global styles should no apply to shadow root elements but for some reason it does. My code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="color-scheme" content="light dark" />
    <title>Vite + Preact</title>
    <style>
      body {
        color: green;
      }
    </style>
  </head>
  <body>
    <div id="app"></div>
    <script type="module" src="/src/index.tsx"></script>
  </body>
</html>

index.tsx

import { render } from 'preact';

import register from 'preact-custom-element';
// import './style.css';

const Greeting = ({ name = 'World' }) => <p>Hello, {name}!</p>;
register(Greeting, 'x-greeting', ['name'], { shadow: true, mode: 'closed' });

export function App() {
  return (
    <div>
      <x-greeting name="Billy Jo"></x-greeting>
    </div>
  );
}

render(<App />, document.getElementById('app'));

and result is text is green

Screenshot 2024-05-06 at 5 42 33 PM Screenshot 2024-05-06 at 5 42 39 PM
marvinhagemeister commented 5 months ago

This is how shadow DOM works. Quoting the specification on how cascading styles works:

The top-level elements of a shadow tree inherit from their host element.

See also this explanation on StackOverflow: https://stackoverflow.com/questions/49709676/light-dom-style-leaking-into-shadow-dom