gpt4 book ai didi

web-component - Lit-Element:如何设置全局/重置 css

转载 作者:行者123 更新时间:2023-12-03 16:22:52 25 4
gpt4 key购买 nike

如果我使用 Lit-element,当前设置全局/重置 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 的项目,您可以很容易地在组件之间共享样式并使用它来执行此重置:

  • 首先为你的共享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%;
    }
    `;


  • 然后在您的组件中导入您的样式


  • 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>`
    }
    }


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

    关于web-component - Lit-Element:如何设置全局/重置 css,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57706814/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com