如何仅将自定义样式应用于特定元素?

时间:2016-11-08 15:34:36

标签: css polymer web-component

我正在开发一个可主题化的Polymer Web组件。根据{{​​3}}文档,我执行以下操作:

  <link rel="import" href="themes/my-element-theme.html">
  <style is="custom-style" include="my-element-theme"></style>

然而,这是一个钝器,因为它将自定义主题应用于我的所有元素。

一种解决方案是将我的所有主题样式范围扩展到CSS类,如下所示:

:root custom-element.my-element-theme {
  font-family: 'Noto Sans', 'Myriad Pro', Calibri, Helvetica, Arial, sans-serif;
}

但是,这使得很难将自定义样式应用于整个文档。

有没有办法更有选择性地将自定义样式应用于元素,比如使用CSS选择器?什么是最佳做法?

1 个答案:

答案 0 :(得分:0)

您绝对可以使用选择器有选择地将样式应用于主题元素。

最好使用自定义属性和mixins并将其值设置为目标元素。这是一个例子:

<!DOCTYPE html>
<html>
<head>
  <link href="http://polygit.org/components/polymer/polymer.html" rel="import" />
  <style is="custom-style">
    .container1 my-elem {
      --my-elem-span: {
        color: red;
      }
    }
    
    .container2 my-elem {
      --my-elem-span: {
        color: blue;
      }
    }
    </style>
</head>
<body>
  <div class="container1">
    <my-elem>hello red</my-elem>
  </div>
  <div class="container2">
    <my-elem>hello blue</my-elem>
  </div>
  
  <dom-module id="my-elem">
    <template>
      <style>
        :host { display: block; }
        
        :host span {
          @apply(--my-elem-span);
        }
      </style>
      
      <span><content></content></span>
    </template>
    
    <script>
      Polymer({
        is: 'my-elem'
      });
    </script>
  </dom-module>
</body>
</html>

您可以通过将css规则放在单独的样式模块中来外化您的样式。

<dom-module id="my-elem-theme">
  <template>
    <style>
      .container1 my-elem {
        --my-elem-span: {
          color: red;
        }
      }

    .container2 my-elem {
      --my-elem-span: {
        color: blue;
      }
    }
    </style>
  </template>
</dom-module>

然后导入你的方式:

<link rel="import" href="my-elem-theme.html">
<style is="custom-style" include="my-elem-theme"></style>
相关问题