当相同的元素出现在同一个地方时,我该如何设置样式?

How i style when same elements in one place?

我在设计组件样式时遇到了问题。当我这样构建我的结构时:

<dom-module id="content-area">
   <template>
      <my-button class='red'>Hello</my-button>
      <my-button class='green'>Hello</my-button>
   </template>
</dom-module>

以及我如何使用外部 html 文件设置样式 custom-style.html

<custom-style>
   <style is="custom-style">
       :host(.red) {
          color: red;
       }
       :host(.green) {
          color: green;
       }
   </style>
</custom-style>

我做错了什么?有什么建议吗?

如果你想使用外部文件来设置你的组件的样式,你必须按照 Polymer 文档中的说明进行操作:https://www.polymer-project.org/2.0/docs/devguide/style-shadow-dom

在你的情况下,你有组件:

<link rel="import" href="custom-style.html">

custom-style.html

<style>
:host(.red) {
          color: red;
       }
       :host(.green) {
          color: green;
       }
</style>

为了使用 custom-style,您可以与所有组件共享: 正如@Alberto Marin 解释的那样,包括样式文件

<link rel="import" href="custom-style.html">
<dom-module id="content-area">
  <template>
    <style include="custom-stle">
    </style>
     <my-button class='red'>Hello</my-button>
     <my-button class='green'>Hello</my-button>
  </template>
</dom-module>

然后在 custom-style.html 处将您的样式块包裹在 和 元素中,如下所示:

<dom-module id="custom-style">
  <template>
    <style>
      <!-- Your shared styles -->
    </style>
  </template>
</dom-module>