Docs

Documentation versions (currently viewingVaadin 14)

You are viewing documentation for an older Vaadin version. View latest documentation

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.

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.

@CssImport(value = "./styles/shared-typography.css",
           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

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.

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

Component Style Scope

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

@CssImport(value = "./styles/shared-styles.css",
           include = "shared-typography",
           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.

// Import a string of shared CSS
import sharedTypography from 'styles/shared-typography.css.js';
import { PolymerElement } from '@polymer/polymer/polymer-element.js';
import { html } from '@polymer/polymer/lib/utils/html-tag.js';

class MyView extends PolymerElement {
  static get template() {
    return html`
      ${sharedTypography}
      <h2>My view title</h2>
      ...
    `;
  }
  static get is() {
    return 'my-view';
  }
}
customElements.define(MyView.is, MyView);

96CC1CBA-FF72-4F10-8393-B49BDB3D1C67