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

标签 css polymer web-component

我正在开发一个可主题化的 Polymer Web 组件。根据 custom-style文档我正在做以下事情:

  <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 选择器?什么是最佳实践?

最佳答案

您当然可以使用选择器有选择地将样式应用到您的主题化元素。

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

<!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>

关于css - 如何仅将自定义样式应用于特定元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40490775/

相关文章:

html - 垂直对齐 css3.尝试了其他一切

javascript - 如何让我的导航出现在我网页的特定部分?

javascript - 高分子简单元件

javascript - 我如何确保 vuex 商店包含在我的构建中?

javascript - 检测 DOM 中 Web 组件的安装

php - 使用 PHP 设置 LESS CSS 颜色

html - 如何防止按钮与 Bootstrap 中的 .btn-group 类相互合并?

polymer - 使用 setAttribute/property 更新模板变量

javascript - Polymer 的基本测试抛出 "You tried to use polymer without loading it first"错误

JavaScript 与 WebComponents/ShadowDOM 封装