Search code examples
polymerweb-component

Polymer: Using selectors


I am using Polymer to create a web component. I want to select the div gutter when the ::host element gets the class full

<link rel="import" href="/polymer/polymer.html">
<dom-module id="smooth-header">
<style>
.full ::content gutter {
  color: red;
}
</style>
<template>
<content>
<div class="gutter"></div>
</content>
</template>
<script>....</script>
</dom-module>

But I am not able to select the gutter element with the above selector.

Why should the above selector fail?

Help with an alternative to select it correctly.


Solution

  • You should use :host(selector) to select a class on the host element:

    :host(.fill) .gutter {
      color: red;
    }
    

    <head>
      <base href="https://polygit.org/polymer+1.5.0/components/">
      <script src="webcomponentsjs/webcomponents-lite.min.js"></script>
      <link rel="import" href="polymer/polymer.html">
    </head>
    <body>
      <x-foo></x-foo>
      <x-foo class="full"></x-foo>
    
      <dom-module id="x-foo">
        <style>
          :host(.full) .gutter {
             color: red;
          }
        </style>
        <template>
          <content>
            <div class="gutter">
              <span>{{foo}}</span>
            </div>
          </content>
        </template>
        <script>
          HTMLImports.whenReady(function() {
            Polymer({
              is: 'x-foo',
              properties : {
                foo: {
                  type: String,
                  value: "Hello world!"
                }
              }
            });
          });
        </script>
      </dom-module>
    </body>

    codepen