css - Bootstrap 4 和 SCSS - 基于基类覆盖主类

标签 css webpack sass bootstrap-4

我正在使用 Bootstrap 4 和 Webpack 构建一个基于一个框架的多站点应用程序。

我想根据 body 元素上的基类动态更改 Bootstrap 的一些变量。即:

.class1{
    $theme-colours: (
        primary: red,
    );
 }

.class2{
    $theme-colours: (
        primary: blue,
    );
 }

然后:

<body class="class1">
    <h1 class="text-primary">RED TEXT</h1> 
</body>

还有:

<body class="class2">
    <h1 class="text-primary">BLUE TEXT</h1> 
</body>

这在 SASS 中可能吗?我尝试过使用 mixin 但没有成功...

最佳答案

您必须使用各种 Bootstrap 4 主题颜色函数/混合来“重建”-primary 类。主要颜色的变化可以进入自定义@mixin,从而更容易构建每个主要“主题”:

@mixin build-primary-classes($color) {
    @include bg-variant(".bg-primary", $color);
    
    .btn-primary {
        @include button-variant($color, $color);
    }
  
    .btn-outline-primary {
        @include button-outline-variant($color);
    }
    
    @include text-emphasis-variant(".text-primary", $color);
    
    .border-primary {
        border-color: $color !important;
    }
}


.theme1 {
    @include build-primary-classes($purple);
}

.theme2 {
    @include build-primary-classes($red);
}

https://codeply.com/go/c3KTMWlDCb

更进一步,您可以将“$customthemes”放入 map 中,然后生成主题类。

$customthemes: (
  "theme1": purple,
  "theme2": cyan,
  "theme3": orange
);

@each $themeName, $color in $customthemes {
  .#{$themeName} {
    @include build-primary-classes($color);
  }
}

https://codeply.com/go/81ukKyAZbS


然后,如果您使用 Webpack,请将 $customthemes 映射传递给 extract-text-webpack-plugin 和 SASS-loader。使用 data 选项传入 $customthemes...

webpack 配置:

     ....
     use: extractSass.extract({
         use: [

                  {
                    loader: "sass-loader",
                    options: {
                      allChunks: true,
                      data: '$customthemes:("theme1":purple,"theme2":pink,"theme3":red);'
                    }
                }]
         })
      .....

请记住,如果您有太多 $customthemes,CSS 将会变得非常大。我更喜欢使用 SASS 生成单独的 theme.css 文件,然后根据需要在 HTML HEAD 中引用任何 theme.css

相关:
How to extend/modify (customize) Bootstrap 4 with SASS
How to change the bootstrap primary color?

关于css - Bootstrap 4 和 SCSS - 基于基类覆盖主类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51820637/

相关文章:

html - 删除 Shopify 中 Google 表单下方的大空白区域(无 Bootstrap )

reactjs - 从 create-react-app 发出构建文件

javascript - ESLint:为什么 Symbol 没有定义(no-undef 规则)?

html - 在内联元素中的下一行显示文本

html - 输入边框 CSS

css - 所有屏幕中的全宽导航菜单

c# - 关于响应式设计的一些建议

javascript - 使用 React-Toolbox 的按钮进行样式设置不起作用

ruby-on-rails - Font-Awesome 5 PRO in rails 5 app

node.js - 在 Node.js 中将 connect-assets 与 SASS 结合使用