【问题标题】:React app - avoiding styles being overridden by other CSSReact 应用程序 - 避免样式被其他 CSS 覆盖
【发布时间】:2019-10-10 19:38:30
【问题描述】:

我想提供一些在用户网站上显示表单的复制和粘贴代码。

所有元素都在“#myContainer”中。

但是,元素样式被用户页面上的其他 CSS 覆盖。

例如,我有一个类为button.MuiButtonBase-root.MuiButton-root.MuiButton-text.MuiButton-textPrimary.jss145 的按钮。我知道我也可以将其定位为 #myContainer 的后代。

但是第三方网站可以通过数百种可能的方式干扰 CSS(例如,字段的背景颜色、按钮的悬停状态)——我的 CSS 中没有一个特别定义。

如果不具体定义每一个可能性,有没有办法可以防止 #myContainer 中的任何内容被外部 CSS 干扰?

非常感谢

【问题讨论】:

标签: css reactjs


【解决方案1】:

我正在使用 css-modules 结合 scss 来限制 css 出血。

index.scss

.mycontainer {
   :global {
       .button.MuiButtonBase-root {
           background: #CCCCCC;
       }
    }
}

MyComponent.js

import styles from './index.scss';

const MyComponent = props => {
  return (
      <div className={styles.mycontainer}>
         <button className="button MuiButtonBase-root">Button</button>
      </div>
  );
};

这将产生一个唯一的父类名称,并且将由 css-loader 在 css 中生成相同的名称。

 <div class="MyComponent__mycontainer-33ds2d3">
     <button className="button MuiButtonBase-root">Button</button>
 </div>

我不知道输出格式是什么,但会类似于MyComponent__mycontainer-33ds2d3,这将确保这些样式不会溢出,反之亦然。

cssModules: true添加css-loader

const autoPrefixer = require('autoprefixer');
const postcssNesting = require('postcss-nested');


{
    test: /src\/(.*)\.(scss)$/,
    use: [
      {
        loader: 'style-loader',
      },
      {
        loader: 'css-loader',
        options: {
          modules: true,
          localIdentName: '[name]__[local]--[hash:base64:5]',
        },
      },
      {
        loader: 'postcss-loader',
        options: {
          ident: 'postcss',
          plugins: () => [autoPrefixer, postcssNesting(/* pluginOptions */)],
        },
      },
      {
        loader: 'sass-loader',
      },
    ],
  },

【讨论】:

  • 很好,感谢您的回复。这将阻止 CSS 流血,但我试图解决的问题是我想不出第三方网站可能设置的所有可能属性(例如背景颜色、悬停状态下的背景颜色......) ...
  • 你能用例子解释你的问题吗?
  • 当然 - nearlyrealflorals.co.uk/testing-forms - 所以“这就是它应该去的地方”下的表单是 React 应用程序。这些字段应该有一个白色的背景。 h4 应该是白色的。但是这些被周围的页面覆盖(例如 input[type=text] )。我可以通过制作更具体的 CSS 声明(例如 #myapp h4 {color: white} )轻松解决这些问题,但我想不出每一个变体,就好像我将代码粘贴到另一个网站上一样,它会有不同的规则。 ..我需要能够防止页面的其余部分干扰我的应用程序容器中的所有内容...
  • @HCapello 你可以尝试将样式设置为* { display: initial; },这样它就不会继承
猜你喜欢
  • 2021-09-28
  • 2014-05-06
  • 1970-01-01
  • 1970-01-01
  • 2015-11-20
  • 2022-01-21
  • 1970-01-01
  • 2013-07-08
  • 1970-01-01
相关资源
最近更新 更多