【问题标题】:Global Utility Classes with PostCSS / CSS Modules具有 PostCSS / CSS 模块的全局实用程序类
【发布时间】:2016-03-13 23:57:36
【问题描述】:

使用CSS Modules,如何在不重复样式声明的情况下将全局实用程序类应用于多个元素?

例如,这是一个没有 CSS 模块的 React 组件。相关行是 div 有两个类:widgetclearfix...

/* components/widget.jsx */

class Widget extends Component {
  render() {
    return (
      <div className="widget clearfix">
        <div className="widget-alpha">Alpha</div>
        <div className="widget-beta">Beta</div>
      </div>
    );
  }
}

.clearfix 是一个全局实用程序类,我想将其应用于整个应用程序的许多元素:

/* util/clearfix.scss */

.clearfix {
  &:before, &:after { content: " "; display: table; }
  &:after { clear: both; }
}

我见过将.clearfix 导入CSS 模块的各种方法,但在每种情况下,样式声明都会针对应用类的每次出现重新定义。这是一个例子:

/* widget.scss */

.widget {
  // other styles
  composes: clearfix from '../util/clearfix.scss';
}

【问题讨论】:

    标签: reactjs webpack postcss css-modules


    【解决方案1】:

    通过反复试验,我发现您可以在使用实用程序类的选择器中声明:global(而不是定义它的位置):

    .widget {
    
      // other styles
    
      :global {
        composes: clearfix;
      }
    }
    

    为了避免混乱和重复的importfrom 语句,我使用index.scss 文件来导入实用程序文件,然后在需要实用程序类的任何部分导入。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-13
      • 2021-06-17
      • 1970-01-01
      • 2016-11-26
      • 2017-03-30
      • 2017-07-01
      • 2019-05-11
      • 2011-07-13
      相关资源
      最近更新 更多