【问题标题】:webcomponents - how to apply external css class to webcomponentwebcomponents - 如何将外部 css 类应用于 webcomponent
【发布时间】:2018-04-11 16:31:22
【问题描述】:

我正在使用webcomponents-lite (Polymer) 创建网络组件。

<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
    <link rel="stylesheet" href="styles.css">
    <script type="text/javascript" src="/static/js/util.js"></script>
</head>
<body class="dark">
    <main>
        <edsp-login-form></edsp-login-form>
    </main>
</body>
</html>

&lt;edsp-login-form&gt; 在使用lit-html 的js 文件中定义。定义如下:

@Define('edsp-login-form', {
  style: ``
})

export class Login extends LitComponent {
render() {
    return html`
    <link rel="import" type="css" href="styles.css">`
    <div></div>
  }
}

在这段代码中,如何将 styles.css 中的 css 类应用到组件 &lt;edsp-login-form&gt;

【问题讨论】:

  • 在 edsp-login.html 中导入 style.css ,它现在可以使用,但很快就会被弃用
  • @NagaSaiA 试过但没用
  • 也许你会对这篇文章感兴趣:stackoverflow.com/a/42764465/4600982

标签: css polymer web-component


【解决方案1】:

选项 1:如果您使用 Shadow DOM,则无法将外部 CSS 应用到您的组件。一种解决方案是通过在您的组件中实现它来停用 Shadow DOM:

createRenderRoot() {
  return this;
}

选项 2:如果您仍想应用外部 CSS 并使用 Shadow DOM,则可以使用 CSS 变量。在您的外部 CSS 中,您可以使用以下方式实例化变量:

name-of-your-component-tag {
  --variable-name-color: #FFF;
}

然后在你的组件中,你可以使用 CSS 变量:

.my-class {
  color: var(--variable-name-color);
}

选项 3: 如果您尝试应用深色主题,则可以在考虑上下文的​​情况下使用组件内部的 CSS。在您的组件中,您可以使用 CSS,例如:

:host-context(.dark) .bg {
  background: #000;
}

【讨论】:

    猜你喜欢
    • 2013-03-27
    • 1970-01-01
    • 1970-01-01
    • 2020-01-23
    • 2012-12-19
    • 2017-08-21
    • 2014-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多