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

3

我正在开发一个可主题化的 Polymer Web 组件。根据自定义样式文档,我正在按照以下步骤进行:

  <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

你肯定可以使用选择器来有选择性地应用样式到可主题化的元素。

最好使用自定义属性和混合(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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接