cayblood
cayblood

Reputation: 1876

How to prevent outside CSS from overriding web component styles

I have a custom Polymer element that I want to style in a certain way and provide as a plugin to many different web sites. I would like to be able to encapsulate my custom components' styles in a way that makes them look the same across all the web sites on which they are embedded. Here is an example of how a font directive from the parent web page is interfering with my component's style:

<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>

Thanks in advance for your help.

Upvotes: 7

Views: 3707

Answers (1)

Timo D
Timo D

Reputation: 1803

There are two ways to achieve this (and you could 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;
}

Also, you can add the !important token to a rule to make it override other rules, however this should be used with care:

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

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

Upvotes: 4

Related Questions