Movatterモバイル変換


[0]ホーム

URL:


Polymer LogoHomeGuidesFeature overviewTry PolymerInstall Polymer 2.xTutorial: Build an element1. Get set up2. Add local DOM3. Data binding & properties4. React to input5. Theming with custom propertiesAbout this releaseWhat's new in 2.0Upgrade guideHybrid elementsRelease notesCustom elementsCustom element conceptsDefine an elementDeclare propertiesShadow DOM & stylingShadow DOM conceptsDOM templatingStyle shadow DOMCustom CSS propertiesEventsHandle and fire eventsGesture eventsData systemData system conceptsWork with object and array dataObservers and computed propertiesData bindingHelper elementsBrowser supportOverviewPolyfillsES6ToolsTools overviewPolymer CLICLI commandsCreate an element projectCreate an application projectDocument your elementsTest your elementsPublish your elementsWeb servicespolymer.json specificationNode supportBuild appsOverviewApp templatesResponsive app layoutRoutingLocalizationApp storageService workerBuild for productionServe your appThe PRPL patternShop App Case StudyNews App Case StudyResourcesGlossaryGlobal settingsAPI ReferenceindexElementsPolymer.ArraySelectorPolymer.CustomStylePolymer.DomBindPolymer.DomIfPolymer.DomModulePolymer.DomRepeatPolymer.ElementClassesPolymer.DebouncerPolymer.DomApiPolymer.FlattenedNodesObserverMixinsPolymer.ArraySelectorMixinPolymer.DirMixinPolymer.ElementMixinPolymer.GestureEventListenersPolymer.LegacyElementMixinPolymer.MutableDataPolymer.OptionalMutableDataPolymer.PropertiesChangedPolymer.PropertiesMixinPolymer.PropertyAccessorsPolymer.PropertyEffectsPolymer.TemplateStampFunctionsPolymer.ClassPolymer.dedupingMixinPolymer.domPolymer.enqueueDebouncerPolymer.flushPolymer.htmlPolymer.htmlLiteralPolymer.importHrefPolymer.mixinBehaviorsPolymer.setLegacyOptimizationsPolymer.setPassiveTouchGesturesPolymer.setRootPathPolymer.setSanitizeDOMValueNamespacesPolymer.ArraySplicePolymer.AsyncPolymer.CaseMapPolymer.domPolymer.GesturesPolymer.PathPolymer.RenderStatusPolymer.ResolveUrlPolymer.SettingsPolymer.StyleGatherPolymer.telemetryPolymer.Templatize

Use custom properties

Edit on GitHub

The Polymer library is in maintenance mode. For new development, we recommendLit.

You're viewing an older version of the Polymer library documentation. Please seePolymer 3.0 for the latest.

Contents

The author of a Polymer element can provide custom CSS properties that you can use to style the appearance of the element in your application.

Custom properties allow CSS authors to define cascading CSS variables, which are accepted by all CSS properties.

CSS variables can be used outside the context of custom elements, simply as a way to avoid scattering style data throughout a stylesheet. A CSS author assigns values to a custom property, and then uses thevar() function to use these values elsewhere in the stylesheet.

This makes editing your CSS much easier and less prone to author error.

For example, the<paper-checkbox> element provides custom properties for styling the colors, spacing and size of the checkbox and its label.

As a developer, you can use these properties to style<paper-checkbox> elements in your applications.

When you create your own custom elements, you can use custom properties to build an interface for the users of your element so they can style it.

Use a custom properties API to style an element

To use the interface of custom properties provided by an element author, look at the element's API documentation.

For a good example, visit the<paper-checkbox> API documentation

This code sample inserts a<paper-checkbox> element with its default styling:

See it on Plunker

<basehref="//polygit2.appspot.com/components/"><linkrel="import"href="polymer/polymer.html"><scriptsrc="webcomponentsjs/webcomponents-lite.js"></script><linkrel="import"href="paper-checkbox/paper-checkbox.html"><paper-checkbox>Check me</paper-checkbox>

Notice that:

  • The checkbox label defaults to Times New Roman. This is true of any web page with no style info.
  • The checkbox receives default colors from the paper-element theme.

The style properties of the<paper-checkbox> element are configurable with the custom CSS properties that the element author has provided for us.

To use a custom property of a custom element, create a style rule using this syntax:

paper-checkbox {  --paper-checkbox-checked-color: red;}

See it on Plunker

The paper elements provide a consistent way to configure styles across elements when using the paper element set, with variables.

We can use variables to configure the custom CSS properties in<paper-checkbox>:

<styleis="custom-style">p {color:var(--paper-red-500);  }paper-checkbox {--paper-checkbox-checked-color:var(--paper-red-500);  }</style>

Create custom properties

Rather than exposing the details of an element's internal implementation fortheming, an element author defines one or more custom CSSproperties as part of the element's API.

These custom properties can be defined similarly to other standard CSS propertiesand will inherit from the point of definition down the composed DOM tree,similar to the effect ofcolor andfont-family.

In the simple example below, the author of<my-toolbar> identified the need forusers of the toolbar to be able to change the color of the toolbar title. Theauthor exposed a custom property called--my-toolbar-title-color which isassigned to thecolor property of the selector for the title element. Usersof the toolbar may define this variable in a CSS rule anywhere up the tree, andthe value of the property will inherit down to the toolbar where it is used ifdefined, similar to other standard inheriting CSS properties.

Example:

<dom-moduleid="my-toolbar"><template><style>:host {padding:4px;background-color: gray;      }.title {color:var(--my-toolbar-title-color);      }</style><spanclass="title">{{title}}</span></template><script>classMyToolbarextendsPolymer.Element{staticgetis() {return"my-toolbar";      }    }    customElements.define(MyToolbar.is, MyToolbar);</script></dom-module>

Example usage of<my-toolbar>:

<dom-moduleid="my-element"><template><style>/* Make all toolbar titles in this host green by default */:host {--my-toolbar-title-color: green;      }/* Make only toolbars with the .warning class red */.warning {--my-toolbar-title-color: red;      }</style><my-toolbartitle="This one is green."></my-toolbar><my-toolbartitle="This one is green too."></my-toolbar><my-toolbarclass="warning"title="This one is red."></my-toolbar></template><script>classMyElementextendsPolymer.Element{staticgetis() {return"my-element";      }    }    customElements.define(MyElement.is, MyElement);</script></dom-module>

The--my-toolbar-title-color property only affects the color of the titleelement encapsulated in<my-toolbar>'s internal implementation. In thefuture the<my-toolbar> author can rename thetitle class orrestructure the internal details of<my-toolbar> without changing the customproperty exposed to users.

You can also include a default value in thevar() function, to use in case the userdoesn't set the custom property:

color:var(--my-toolbar-title-color,blue);

To include a default value that is a custom property, use this syntax:

color:var(--my-color,var(--my-default-color))

Thus, custom CSS properties are a powerful way for element authors toexpose a theming API to their users in a way that naturally fits right alongsidenormal CSS styling.

Use custom CSS mixins

It may be tedious (or impossible) for an element author to predict everyCSS property that may be important for theming, let alone expose everyproperty individually.

CSS mixins are a proposal to fill this gap in functionality. To use CSS mixins, import the CSS mixins polyfill:

<!-- import CSS mixins polyfill --><linkrel="import"href="/bower_components/shadycss/apply-shim.html">

For backward compatibility, thepolymer.html import includes the CSS mixins polyfill. No extra import is required when defining hybrid elements.

Using CSS mixins, an element author can define a set of CSS properties as a single custom property and then allow all properties in the set to be applied to a specific CSS rulein an element's shadow DOM. The extension enables this with a mixin capabilitythat is analogous tovar, but which allows an entire set of propertiesto be mixed in.

Use@apply to apply a mixin:

@apply --mixin-name;

Defining a mixin is just like defining a custom property, but thevalue is an object that defines one or more rules:

selector {  --mixin-name: {    /* rules */  };}

Example:

<dom-moduleid="my-toolbar"><template><style>      :host {        padding: 4px;        background-color: gray;        /* apply a mixin */        @apply --my-toolbar-theme;      }      .title {        @apply --my-toolbar-title-theme;      }</style><spanclass="title">{{title}}</span></template>  ...</dom-module>

Example usage ofmy-toolbar:

<dom-moduleid="my-element"><template><style>/* Apply custom theme to toolbars */:host {--my-toolbar-theme: {          background-color: green;border-radius:4px;border:1px solid gray;        };--my-toolbar-title-theme: {color: green;        };      }/* Make only toolbars with the .warning class red and bold */.warning {--my-toolbar-title-theme: {          color: red;font-weight: bold;        };      }</style><my-toolbartitle="This one is green."></my-toolbar><my-toolbartitle="This one is green too."></my-toolbar><my-toolbarclass="warning"title="This one is red."></my-toolbar></template><script>classMyElementextendsPolymer.Element{staticgetis() {return"my-element";      }    }    customElements.define(MyElement.is, MyElement);</script></dom-module>

Use CSS inheritance

If an element doesn't override styling information, that element inherits styles from its parent:

<linkrel="import"href="components/polymer/lib/elements/custom-style.html"><custom-style><styleis="custom-style">p {color:var(--paper-red-900);font-family: Sans-serif;    }paper-checkbox {--paper-checkbox-checked-color:var(--paper-red-900);    }</style></custom-style><body><p><paper-checkbox>Check me</paper-checkbox></p></body>

Create global styles

Create global styles by styling the the html element of your document:

<linkrel="import"href="components/polymer/lib/elements/custom-style.html"><custom-style><styleis="custom-style">html {font-family: Sans-serif;--my-color:var(--paper-red-900);color:var(--my-color);    }paper-checkbox {--paper-checkbox-checked-color:var(--my-color);    }</style></custom-style>

Note that the font family is inherited, but the text color is not. This is because<paper-checkbox> overrides the text color.

Custom property API for Polymer elements

Polymer's custom property shim evaluates and applies custom property values onceat element creation time. In order to have an element (and its subtree) re-evaluate custom property values due to dynamic changes such as application ofCSS classes, call theupdateStylesmethod on the element. To updateall elements on the page, you can also callPolymer.updateStyles.

updateStyles can take a object with property/value pairs to update the current values ofcustom properties.

Example:

<dom-moduleid="x-custom"><template><style>:host {--my-toolbar-color: red;      }my-toolbar {background-color:var(--my-toolbar-color);      }</style><my-toolbar>My awesome toolbar</my-toolbar><buttonon-click="changeTheme">Change theme</button></template><script>classXCustomextendsPolymer.Element{staticgetis() {return"x-custom";      }      changeTheme() {this.updateStyles({'--my-toolbar-color':'blue',        });      }    }    customElements.define(XCustom.is, XCustom);</script></dom-module>
this.updateStyles({  '--some-custom-style': 'green',  '--another-custom-style': 'blue'});

Occasionally an element needs to get the value of a custom property at runtime. This is handledslightly differently depending on whether the shady CSS polyfill is loaded:

if (ShadyCSS) {  style = ShadyCSS.getComputedStyleValue(this,'--something');}else {  style = getComputedStyle(this).getPropertyValue('--something');}

Elements using the legacy API can use thegetComputedStyleValueinstance method instead of testing forShadyCSS.

Custom properties shim limitations

Cross-platform support for custom properties is provided in Polymer by aJavaScript library thatapproximates the capabilities of the CSS Variablesspecificationfor the specific use case of theming custom elements, whilealso extending it to add the capability to mixin property sets to rules asdescribed above. For performance reasons, Polymerdoesnot attempt to replicate all aspects of native custom properties.The shim trades off aspects of the full dynamism possible in CSS in theinterests of practicality and performance.

Below are current limitations of the shim. Improvements to performance anddynamism will continue to be explored.

Dynamism limitations

Only property definitions which match the element atcreation time are applied.Any dynamic changes that update property values are not applied automatically. Youcan force styles to be re-evaluated by calling theupdateStyles method on aPolymer element, orPolymer.updateStyles to update all elementstyles.

For example, given this markup inside an element:

HTML:

<divclass="container"><x-fooclass="a"></x-foo></div>

CSS:

/* applies */x-foo.a {--foo: brown;}/* does not apply */x-foo.b {--foo: orange;}/* does not apply to x-foo */.container {--nog: blue;}

After adding classb tox-foo above, the host element must callthis.updateStylesto apply the new styling. This re-calculates and applies styles down the tree from this point.

Dynamic effectsare reflected at the point of a property's application.

For the following example, adding/removing thehighlighted class on the#title element willhave the desired effect, since the dynamism is related toapplication of a custom property.

#title {background-color:var(--title-background-normal);}#title.highlighted {background-color:var(--title-background-highlighted);}

Inheritance limitations

Unlike normal CSS inheritance which flows from parent to child, customproperties in Polymer's shim can only change when inherited by a custom elementfrom rules that set properties in scope(s) above it, or in a:host rule forthat scope.Within a given element's local DOM scope, a custom property canonly have a single value. Calculating property changes within a scope would beprohibitively expensive for the shim and is not required to achieve cross-scopestyling for custom elements, which is the primary goal of the shim.

<dom-moduleid="my-element"><template><style>:host {--custom-color: red;     }.container {/* Setting the custom property here will not change *//* the value of the property for other elements in  *//* this scope.                                      */--custom-color: blue;     }.child {/* This will be always be red. */color:var(--custom-color);     }</style><divclass="container"><divclass="child">I will be red</div></div></template><script>classMyElementextendsPolymer.Element{staticgetis() {return"my-element";      }    }    customElements.define(MyElement.is, MyElement);</script></dom-module>

Styling distributed elements not supported

The custom properties shim doesn't support styling distributed elements.

/* Not supported */:host::slotted(div) {--custom-color: red;}

[8]ページ先頭

©2009-2025 Movatter.jp