【问题标题】:Bootstrap 4 & SCSS - Overide Primary Based on Base ClassBootstrap 4 & SCSS - 基于基类覆盖主要
【发布时间】:2019-01-20 02:00:57
【问题描述】:

我正在使用 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 但没有成功...

【问题讨论】:

  • 是的,如果你通过 js 使用 webpack 它的句柄
  • @Noni 知道怎么做吗?

标签: css webpack sass bootstrap-4


【解决方案1】:

您必须使用各种 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”放入地图中,然后生成主题类。

$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?

【讨论】:

    猜你喜欢
    • 2019-03-27
    • 2020-05-13
    • 2018-01-20
    • 1970-01-01
    • 1970-01-01
    • 2020-02-28
    • 2020-04-02
    • 2017-01-11
    • 2019-03-31
    相关资源
    最近更新 更多