0
votes

First of all, sorry for yet another post about this topic but I couldn't see anything that makes sense to me in polymer documentation and on stackoverflow.

I just want to attach style to my element.

From the documentation (https://www.polymer-project.org/0.5/articles/styling-elements.html and https://www.polymer-project.org/0.5/docs/polymer/styling.html#including-stylesheets-in-an-element)it should be straight forward.

 <polymer-element name="x-foo">
 <template>
 <style>
   x-foo div { ... }
 </style>
 ...

But it doesn't work as expected. If we define the style for an element, inside the element, it is not applied.

Here is the code:

  <polymer-element name="x-button" noscript>
    <template>

      <style>
        /* not working */
        x-button {
          background-color: green;
        }

        /* not working */
        x-button .hithere{
          display: block;
          min-height: 50px;
          background-color: red;
          margin: 20px;
        }

        /* not working */
        x-button .hitheretoo{
          display: block;
          min-height: 50px;
          background-color: blue;
          margin: 20px;
        }
      </style>


      <div class="hithere"></div>

      <template>
        <div class="hitheretoo"></div>
      </template>


    </template>

  </polymer-element>

And a live demo: http://codepen.io/anon/pen/yyZqMN

Thanks

2

2 Answers

0
votes

Use the :host selector when styling an element from inside itself

<style>
  :host {
    background-color: green;
  }

  .hithere {
    display: block;
    min-height: 50px;
    background-color: red;
    margin: 20px;
  }

  .hitheretoo {
    display: block;
    min-height: 50px;
    background-color: blue;
    margin: 20px;
  }
</style>

When you're styling from inside a custom element all selectors are already scoped to the element. By selecting x-button you are selecting any x-buttons that are descendants of this element, not the element itself. That also means you don't need to prefix selectors with the tag name to scope them; the shadow DOM provides scoping.

1
votes

ssorallen explained the css issue very well and there is more. I couldn't get :host to work on it's own and depending on the browsers you will need to shim the Shadow DOM & add polyfill-next-selector styles.

Additionally, The element never gets registered because you have not used the Polymer() function inside the custom element (unless you chose not to add it in your code example). Here is a codepen of what I found to be one possible solution.

The one thing I am still trying to figure out is the nested <template> issue. I can't pierce the shadow boundary with ::shadow or /deep/. Might be a bug. I'll take a look when I get a few minutes.