How to exclude global styles in a React App?

和自甴很熟 提交于 2020-07-22 03:54:25

问题


I am using Material UI for building my React Project.

However there is a component which has to be embedded to a different site. Meaning, I am providing the production build of this component to embed it to a different site.

My React app's css is getting overridden by the global styles defined in that website.

I don't want this behaviour. Is there any way I can isolate the css of my react app and the global css of the other website.

I saw this question but the solutions didn't help me.


回答1:


If iframes and Web Components are out of the question, the only remaining option is CSS resets.

Create a CSS class and a series of rules that reset the styles of any elements that occur inside that class.

.my-reset {
  /* Global resets (e.g. font family) */
}

.my-reset p {
  /* Reset paragraph styles */
}

.my-reset label {
  /* Reset label styles */
}

/* etc. */

Apply that class to the root-level component:

function MyApp() {
    <div className="my-reset">
        { /* app goes here */ }
    </div>
}

There are plenty of CSS reset libraries out there. Since you have no control over global styles, you're going to have to be heavy handed with the resets. So if it's at all possible, make your component embeddable as an iframe.




回答2:


I see multiple solutions to this problem

  1. Use !important in those styles possible.
  2. Use id to give styling instead of class, as id has higher presidence.
  3. If you give more specific styling to the elements then the build file css will override the outer site's css, i.e like if we write our css like .parent#child this is more specific styling and it will override the wrapper site's css.

Check this out https://stuffandnonsense.co.uk/archives/css_specificity_wars.html




回答3:


There's another sort of scrappy solution that you could use in the case where you don't need the old table style and the new Material-UI tables on the same HTML page.

If you own the site that you are trying to embed the React app in (i.e., you have control over the new environment's CSS), another thing you could do to reset the CSS styles for the components in your app is to remove the classes that are overwriting your styles.

For example, if you're using Material-UI tables and your existing table styles are affecting the render, you could put the existing table styles into a separate CSS file that you only import when you render your existing tables, on another HTML page.



来源:https://stackoverflow.com/questions/57636729/how-to-exclude-global-styles-in-a-react-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!