Lit-Element: 如何设置 global/reset css

Lit-Element: How do I set global/reset css

如果我使用 Lit-element,当前设置 global/reset CSS 的最佳做法是什么?

我已经尝试过 1) 在我的文档根目录的 <style> 中内联它们,2) 像这样构建样式表 answer

<script>
  var css = new CSSStyleSheet()
  css.replace('@import url("./style/static/reset.css")')
  document.adoptedStyleSheets = [css]
</script>

但没有任何效果...

编辑 我的 reset.css:

blockquote,
body,
dd,
dl,
fieldset,
figure,
h1,
h2,
h3,
h4,
h5,
h6,
hr,
legend,
p,
pre,
button,
ul {
  margin: 0;
  padding: 0;
}

img {
  max-width: 100%;
}

我在 https://open-wc.org/guide/#quickstart

搭建的文件夹结构之上构建

这不会像您预期的那样工作,因为 LitElement 默认使用 Shadow DOM 旨在防止外部 CSS 影响组件的内部树(反之亦然)

影响 Web 组件内部样式的唯一方法是组件使用 CSS 变量,或者如果继承样式的属性在 Web 组件内部未定义(有关详细信息,请查看 this guide

但是,如果这是一个完全基于 LitElement 的项目,您可以很容易地在组件之间共享样式并使用它来进行此重置:

  1. 首先为您的共享 css 创建一个 js 文件(例如 reset-css.js)

import { css } from 'lit-element';

export default css `
blockquote,
dd,
dl,
fieldset,
figure,
h1,
h2,
h3,
h4,
h5,
h6,
hr,
legend,
p,
pre,
button,
ul {
  margin: 0;
  padding: 0;
}

img {
  max-width: 100%;
}
`;

  1. 然后在你的组件中导入你的样式

import {LitElement, html, css} from 'lit-element';

// include your reset styles
import resetCSS from './reset-css.js';

class MyComponent extends LitElement {

  static get styles() {
    // this is the important part, this array includes our resetted styles and this components styles
    return [
      resetCSS, 
      css`
        h1 {
          color: blue;
        }
      `
    ]; 
  }
  
  render() {
    html`<h1>Something Blue</h1>`
  }
}

就像那样,任何包含共享重置样式的组件都将使用它们