Shared CSS

Polymer elements use Shadow DOM and their styles don’t overlap with each other. It’s a very useful feature, but sometimes you may want to share some CSS between elements.

Let’s examine an example of how to re-use CSS.

First of all we need to create an element that contains common styles we want to share.

src/recipes/convention/css/shared-styles.html
<dom-module id="shared-styles">
  <template>
    <style>
      /* Mixins and variables cannot be declared just inside <style/> tag. */
      /* We should declare them inside some selector. */
      /* :host > * is a good place to put global variables. */
      :host > * {
        /* CSS variable */
        --white-color: white;
      }

      .blue-block {
        background-color: #006ba9;
      }
    </style>
  </template>
</dom-module>

So, we have declared a class and a variable with a color. Now, we can use them in other components.

src/recipes/convention/css/blue-button.html
<link rel="import" href="../../../../bower_components/polymer/polymer-element.html">
<!-- Import file with styles in order to use them -->
<link rel="import" href="shared-styles.html">

<dom-module id="blue-button">
  <template>
    <!-- The styles below extend shared-styles.html -->
    <style include="shared-styles">
      .blue-block {
        border: none;
        border-radius: 3px;
        /* We use variable declared in shared-styles.html */
        color: var(--white-color);
        padding: 10px 15px;
      }
    </style>

    <!-- The button is blue because the color is specified in shared-styles.html -->
    <button class="blue-block">I'm a button and I'm proud of it!</button>

  </template>
  <script>
    class BlueButton extends Polymer.Element {
      static get is() {
        return 'blue-button';
      }
    }

    customElements.define(BlueButton.is, BlueButton);
  </script>
</dom-module>

The resulting blue-button element looks as follows: