How to prevent external CSS from overriding web component styles

I have a custom Polymer element that I want to style in a specific way and provide it as a plugin to many different websites. I would like to be able to encapsulate the styles of my custom components in such a way that they look the same across all websites where they are embedded. Here's an example of how the font directive from the parent web page interferes with my component styling:

<style>
* {
  font-size: 18px;
}
</style>
<script src="http://www.polymer-project.org/webcomponents.js"></script>
<link rel="import" href="http://www.polymer-project.org/components/polymer/polymer.html">

<polymer-element name="polymer-css-test">
  <template>
    <style>
      :host {
        font-size: 12px;
      }
    </style>
    <div>
      Please tell me how to make this 12pt.
    </div>
  </template>
  <script>
    Polymer('polymer-css-test', {
      ready: function () {
      }
    });
  </script>
</polymer-element>
<polymer-css-test></polymer-css-test>
      

Run codeHide result


Thanks in advance for your help.

+3


source to share


1 answer


There are two ways to achieve this (and you can even use both).

If you want your style rules to apply here, you need to make them more specific than the "global" rules:

:host * {
    font-size: 12px;
}

      



Alternatively, you can add a token !important

to a rule to force it to override other rules, however this should be used with caution:

:host {
    font-size: 12px!important;
}

      

For more information on Specificity (which rules apply to which elements), check this page .

+1


source







All Articles