Den
Den

Reputation: 1472

How to prevent outside CSS from adding and overriding ReactJS component styles

I have a custom ReactJS component that I want to style in a certain way and provide as a plugin to many different web sites. But when web sites use global styles (Twitter bootstrap or another css framework) it adds and overrides styles of my component. For example:

global.css:

    label { 
        color: red;
        font-weight: bold;
     }

component.js:

class HelloMessage extends React.Component {
  render() {
      let style = {
          color: "green"
      };
    return (<label style={style}>Hello</label>);
  }
}

result:

enter image description here

Above I didn't use "font-weight: bold" in my component's style but in result my component is using it.

I'd like to be able to encapsulate my custom components's styles in a way that makes them look the same across all the web sites.

Upvotes: 5

Views: 6552

Answers (1)

Richard Rutsche
Richard Rutsche

Reputation: 1206

The best approach in my view is to define some kind of reset class for your component and put in a set of css resets you can find out there (e.g. http://meyerweb.com/eric/tools/css/reset/)

The definition in a sass file could look like this:

.your-component-reset {
    div, span, object, iframe {
        margin: 0;
        padding: 0;
        border: 0;
        font-weight: normal;
        font-size: 100%;
        font: inherit;
        vertical-align: baseline;
    }
    // add some more reset styles
}

To avoid writing a lot when you don't want to use sass just use the universal selector *:

.your-component-reset * {
     margin: 0;
     padding: 0;
     font-weight: normal;
     // other reset styles ...
}

Upvotes: 1

Related Questions