造型聚合物元素的可扩展设置

Scalable setup for styling polymer elements

似乎对于造型聚合物 1.0 元素基本上有两种选择:

  1. 样式通过 自定义样式:

样式可以应用于 <style is="custom-style">...</style> 部分。在此,您可以调整预定义的样式。

  1. 通过 dom-module 元素设置样式:

另一个例子是,您可以通过调整文件中元素本身的元素来调整该元素的样式,调整 <dom-module id="xx"><template>...</template></dom-module>

第二种方法允许更严格的更改。但是,第二种方法需要编辑 polymer HTML 文件本身。如果您 运行 Polymer via bower includes 这意味着每次更新标记文件时,所有更改都会被覆盖。

其他人是否有处理 Polymer 样式的经验,是否有另一种方法可以在不调整 Polymer 源文件的情况下进行严格的更改?

Polymer 支持 CSS mixins and CSS variables,这将允许元素作者公开样式点,用户可以在不修改原始源的情况下自定义这些样式点。

以下示例元素定义默认样式,然后应用给定的 CSS mixin (--x-foo-body)(如果可用):

<dom-module id="x-foo">
  <template>
    <style>
      .body {
        padding: 1em;
        font-size: 0.9em;
        @apply --x-foo-body;
      }
    </style>
    <p class="body">Lorem ipsum...</p>
  </template>
  ...

此元素的用户可以通过使用 custom-style 更改 .body 的元素样式(注意:[=19= 中不需要 is="custom-style" ]):

// index.html
<style is="custom-style">
  x-foo.my-styles {
    --x-foo-body: {
      padding: 0;
      color: red;
    };
  }
</style>

<x-foo class="my-styles"></x-foo>

CSS 变量遵循相同的想法。此示例元素为其标题文本使用 blue 的默认 font-color,但允许它被名为 --x-foo-heading-color.

的 CSS 变量覆盖
<dom-module id="x-foo">
  <template>
    <style>
      .heading {
        color: var(--x-foo-heading-color, blue);
      }
    </style>
    <h2 class=".heading">Hello world</h2>
    <p>Lorem ipsum...</p>
  </template>
  ...

并且用户可以使用 custom-style 更改元素的标题颜色(注意:dom-module 中不需要 is="custom-style"

// index.html
<style is="custom-style">
  x-foo.my-heading-style {
    --x-foo-heading-color: green;
  }
</style>

<x-foo class="my-heading-style"></x-foo>

<head>
  <base href="https://polygit.org/polymer+1.7.0/components/">
  <script src="webcomponentsjs/webcomponents-lite.min.js"></script>
  <link rel="import" href="polymer/polymer.html">
  
  <dom-module id="x-foo">
    <template>
      <style>
        .heading {
          font-family: sans-serif;
          color: var(--x-foo-heading-color, gray);
        }
        .body {
          padding: 1em;
          font-size: 0.9em;
          @apply --x-foo-body;
        }
      </style>
      <h2 class="heading">[[heading]]</h2>
      <p class="body">Lorem ipsum...</p>
    </template>
    <script>
      HTMLImports.whenReady(function() {
        Polymer({ is: 'x-foo' });
      });
    </script>
  </dom-module>

</head>
<body>
  <style is="custom-style">
    .x-heading {
      --x-foo-heading-color: green;
    }
    .x-body {
      --x-foo-body: {
        padding: 0.5em;
        font-family: Courier New;
        background-color: lightgray;
      };
    }
  </style>

  <x-foo heading="Default style"></x-foo>
  <x-foo heading="Custom heading color" class="x-heading"></x-foo>
  <x-foo heading="Custom heading color and body styles" class="x-heading x-body"></x-foo>
</body>

codepen

您可以在 Polymer docs 中阅读有关主题元素的更多信息。