Sharing Style Sheets

Avoid copy-pasting the same CSS in multiple style sheets.

You can share a style sheet between the global scope and multiple component scopes. One common use case for shared style sheets is to define typographic styles which you want to be applied consistently across the whole application.

Prerequisites

You should be familiar with Style Scopes and Importing Style Sheets.

Creating Shared Style Sheets

To be able to share styles across many style scopes, you need to create a shared style sheet.

JavaJavaScript

If you want to share style sheets in server-side views (Java), place the shared styles in a separate .css file. You make it shareable by using the @CssImport annotation and giving it a unique id. The style sheet will not be imported to any scope until another style sheet includes it using the id.

ImportingStyleSheets.java

shared-typograhy.css

Expand code

  1. @CssImport(value = "./styles/shared-typography.css",
  2. id = "shared-typography")

Using Shared Style Sheets

Once you have created and defined a shared style sheet, you can include it in another style sheet which you can import either to the global style scope or to a component’s local style scope.

Global Style Scope

JavaJavaScript

In server-side views (Java), reference the id of the shared style sheet in the include attribute of the @CssImport annotation. This will include the shared style sheet in the global scope, together with the other style sheet the annotation references using the file path.

ImportingStyleSheets.java

Expand code

  1. @CssImport(value = "./styles/shared-styles.css",
  2. include = "shared-typography")

Component Style Scope

JavaJavaScript

To use a shared style sheet in a component scope, add the include attribute to a component scoped @CssImport annotation.

ImportingStyleSheets.java

Expand code

  1. @CssImport(value = "./styles/shared-styles.css",
  2. include = "shared-typography",
  3. themeFor = "vaadin-confirm-dialog-overlay")

If you want to share a style sheet with a custom web component or client-side template, import it in the template directly.

JavaScript

ImportStyleSheets.js

Expand code

  1. // Import a string of shared CSS
  2. import sharedTypography from 'styles/shared-typography.css.js';
  3. import { PolymerElement } from '@polymer/polymer/polymer-element.js';
  4. import { html } from '@polymer/polymer/lib/utils/html-tag.js';
  5. class MyView extends PolymerElement {
  6. static get template() {
  7. return html`
  8. ${sharedTypography}
  9. <h2>My view title</h2>
  10. ...
  11. `;
  12. }
  13. static get is() {
  14. return 'my-view';
  15. }
  16. }
  17. customElements.define(MyView.is, MyView);